# vue 元件基礎和生命週期 4 ###### tags: `vue` ### 元件基礎: 在用vue開發一定會用到components(元件),每個元件都有統一的架構,如下圖  template:裡要放一個div包住所有標籤,該div裡再放html語法、vue語法,不然會出錯。 script:裡面放js語法,和生命週期之類的應用。 style:放css語法,也可以外部引入,scoped是指該css指套用到該元件,以防多元件之間的css有衝突問題。 ### 元件引用: 我們現在要在lifecirlce.vue,引入HelloWorld.vue(此元件一開始便幫你創建好了), 只需在lifecirlce.vue裡的script裡打 `import hello from ''@/components/HelloWorld.vue'` hello 可自訂名稱 接著在components裡輸入 `hello` 然後在template裡打 `<hello />` 就可以成功引入元件了 以下是程式碼 ``` <template> <div class="home"> <input v-model="test" type="text" > <hello /> </div> </template> <script> import hello from '@/components/HelloWorld.vue' // @ is an alias to /src /*eslint-disable*/ export default { name: 'lifecircle', components: { hello }, data:()=>({ test:"這是元件一" }), } </script> ``` ### 生命週期: Vue有兩個基本要素,要被掛載的「元素」(el)跟「資料」(data)。有了這兩個設定,就可以進行基本操作。 元素是指template裡的html元素 資料是指data裡的東西 元件在生成時,會有生命週期,就像人的生老病死一樣。 Vue的生命週期有(由先至後)beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、beforeDestroy、destroyed 如下圖  beforeCreate: 完成實例初始化,在這階段是data跟el都是undefined created: 這時候 data, computed, methods, watch… 中的值都已被創建出來,但 el尚未創建。 beforeMount: el 已經被創建,尚未被掛在到頁面上 mounted: 頁面已經加載完成 beforeUpdate: 當我們修改data裡的內容前,還未被描繪在頁面 上,就會執行此段程式, updated: 當我們修改data裡的內容後並呈現在頁面上,就會執行此段程式 beforeDestroy: 當我們離開該元件的頁面前,就會執行此段程式 destroyed: 當我們離開該元件的頁面後,同時使用的各種事件與監聽都會被解除,就會執行此段程式
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up