Vue元件使用基礎
阿新 • • 發佈:2018-11-14
這篇博文用來記錄
.vue
元件的使用方法。
可以把元件程式碼按照 template
、style
、script
的拆分方式,放置到對應的 .vue
檔案中。
模板(template
)、初始資料(data
)、接受的外部引數(props
)、方法(methods
)、生命週期鉤子函式(lifecycle hooks
)。
基本步驟
在 html
中使用元件
<div id="app"> <my-component></my-component> </div>
使用元件首先需要建立構造器:
var myComponent = Vue.extend({
template: `<p>myComponent</p>`
})
要把這個構造器用作元件,需要用 Vue.component(tag, constructor)
註冊 :
全域性註冊
// 全域性註冊元件,tag 為 my-component
Vue.component('my-component', myComponent)
Vue.component('my-component', MyComponent)
這種是全域性註冊
選項物件的template
屬性用於定義元件要渲染的HTML
;
區域性註冊
new Vue({
el: '#app',
components: {
'my-component': myComponent
}
})
子元件只能在父元件的template
中使用。
元件選項問題
在定義元件的選項時,data
和 el
選項必須使用函式。
如果data
選項指向某個物件,這意味著所有的元件例項共用一個data
。
所以應當使用一個函式作為 data
選項,讓這個函式返回一個新物件:
Vue.component('my-component', { data: function () { return {a: 1} } });
同理,el
選項用在 Vue.extend()
中時也須是一個函式。
資料傳遞
Vue.js元件之間有三種資料傳遞方式:
- props
- 元件通訊
- slot
props
props是元件資料的一個欄位,期望從父元件傳下來資料。因為元件例項的作用域是孤立的,所以子元件需要顯式地用props
選項來獲取父元件的資料。
props
選項可以是
字面量、
表示式、
繫結修飾符。
字面量
<div id="app">
<child msg="hello!"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
Vue.component('child', {
props: ['msg'],
// prop 可以用在模板內
// 可以用 this.msg 設定
template: `<span>{{msg}} Are you tired?</span>`
});
new Vue({
el: "#app"
})
</script>
HTML
特性不區分大小寫。名字形式為 camelCase
的 prop
用作特性時,需要轉為 kebab-case
(短橫線隔開):
<div id="app">
<child my-message="hello!"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
Vue.component('child', {
props: ['myMessage'],
template: `<span>{{myMessage}} Are you tired?</span>`
});
new Vue({
el: "#app"
})
</script>
動態
用 v-bind
繫結動態 props
到父元件的資料。每當父元件的資料變化時,也會傳導給子元件。
<div id="app">
<input v-model="parentMsg"><br>
<child :my-message="parentMsg"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
Vue.component('child', {
props: ['myMessage'],
template: `<span>{{myMessage}} Are you tired?</span>`
});
new Vue({
el: "#app",
data: {
parentMsg: 'hello!'
}
})
</script>
繫結型別
可以使用繫結修飾符:
.sync
,雙向繫結.once
,單次繫結
<!-- 預設為單向繫結 -->
<child :msg="parentMsg"></child>
<!-- 雙向繫結 -->
<child :msg.sync="parentMsg"></child>
<!-- 單次繫結 -->
<child :msg.once="parentMsg"></child>
prop
預設是單向繫結:當父元件的屬性變化時,將傳導給子元件,但是反過來不會。
不過需要注意的是:如果 prop
是一個物件或陣列,是按引用傳遞。在子元件內修改它會影響父元件的狀態,不管是使用哪種繫結型別。
prop型別驗證
Vue.component('example', {
props: {
propA: Number,// 基礎型別檢測 (`null` 任何型別)
propM: [String, Number],// 多種型別 (1.0.21+)
propB: {// 必需且是字串
type: String,
required: true
},
propC: {// 數字,有預設值
type: Number,
default: 100
},
propD: {// 物件|陣列的預設值應當由一個函式返回
type: Object,
default: function () {
return {msg: 'hello'}
}
},
propE: {
// 指定這個 prop 為雙向繫結
// 如果繫結型別不對將丟擲一條警告
twoWay: true
},
propF: {// 自定義驗證函式
validator: function (value) {
return value > 10
}
},
propG: {
// 轉換函式(1.0.12 新增)
// 在設定值之前轉換值
coerce: function (val) {
return val + '';// 將值轉換為字串
}
},
propH: {
coerce: function (val) {
return JSON.parse(val);// 將 JSON 字串轉換為物件
}
}
}
});