注冊一個組件
有兩種方式可以注冊一個組件,第一種是全局注冊,第二種是局部注冊
# 全局注冊Vue.component('my-component',{ template: '<span>Hello</span>'})# 局部注冊var child = { template: '<span>Hello</span>'}new Vue({ // ??? components:{ my-component: child }})注意:組件的注冊必須要在Vue實例創建之前
使用組件
<div id="app"> <my-component></my-component></div>
當我們需要使用到data時,data必須是一個函數,否則將會報錯,這是Vue的一個規則,如下
Vue.component('my-component',{ template: '<span>{{message}}</span>', data:function(){ return {message:'hello'} }})組件間消息傳遞
當我們封裝了組件A,但是組件A又嵌套了組件B,這時候組件AB形成了父子組件的關系,我們應該怎么來讓父組件傳遞消息給子組件呢,這里用到了一個屬性值props,如下
Vue.component('my-component',{ props: ['message'] template: '<span>{{message}}</span>'})# 通過props傳遞消息給子組件<my-component message="Hello"></my-component>上面的例子,我們通過props傳遞了參數給子組件,確實能改變子組件的值,但是,假如我們有這樣一個要求,props的值是動態改變的,那么這種靜態字面量傳遞參數的方式就不能滿足我們的需求了。如下將說明如何進行動態的props值設定
<div id="app"> <input v-model="parentMsg"><br> <my-component v-bind:message="parentMsg"></div>
這里通過v-bind的命令,將我們的message與parentMsg進行綁定,這樣,當我們的parentMsg改變時,message將能實時改變
自定義事件
父子組件之間如果通過props來傳遞數據的話,那么似乎只能進行單向的數據傳遞,只能從父組件向子組件傳遞,假如我們需要從子組件傳遞消息回去,那么就需要用到自定義事件了
# 使用v-on綁定自定義事件Vue.component('my-component',{ template: '<button v-on:click="increment">{{counter}}</button>', data: function(){ return {counter: 0} }, methods: { increment: function(){ this.counter += 1; this.$emit(increment); } }})new Vue({ el: '#app', data: { // ??? total:0 }, methods: { // ??? incrementTotal: function(){ this.total += 1; } }})<div id="app"> // ??? <p>{{total}}</p> <my-component v-on:increment="incrementTotal"></my-component></div>這里,我們點擊按鈕,按鈕的顯示的數值將會改變,同時,total的值也會動態的改變,這就是子組件回傳數據的實例,我們點擊按鈕時,將會首先執行button的onclick方法,在onclick方法里面,通過this.$emit('increment')來執行我們自定義的事件,假如我們需要在$emit中添加參數,那么我們就要在$on()中進行回調的處理
我們接下來自定義一個表單輸入控件,我們在輸入框中輸入信息,同時在P標簽中顯示出來。
這里我們平時使用的
v-model="message"
其實是下面語句的一個簡化版本,也就是語法糖
v-bind:value="message" v-on:input="message = arguments[0]"
或者
v-bind:value="message" v-on:input="message = $event.target.value"
那么自定義表單控件我們需要干什么呢?
為了讓v-model生效,我們需要在子組件中定義一個value的屬性,還有一個監聽新值產生的input事件
來看看我們的自定義控件
在上面,我們通過 :value="message" 綁定一個value使其與上一級組件的message相掛鉤,后面這個 v-on:input 是子組件定義的事件,事件名可以自己定義,arguments[0] 是組件自定義時傳入的第一個參數
完整代碼如下:
# 使用自定義事件的表單輸入控件Vue.component('my-input',{ template: '/ <div>/ <label>{{label}} :</label>/ <input v-bind:value="value" v-on:input="onInput"></input>/ </div>/ ' , props:['value','label'], methods:{ onInput:function(event){ this.$emit('input',event.target.value); // this.$emit('input') } }})<div id="app"> <p>{{message}}</p> <my-input label="Message" v-model="message"></my-input><br> <!-- <my-input label="Message" :value="message" @input="message = arguments[0]"></my-input> --></div>我們在定義內部事件時,調用到了$emit(),為了讓message能動態改變,我們需要將輸入的參數回傳回去,這樣才能使外部組件與我們的表單控件顯示一致
Vue組件的就先寫到這,接下來還有事件分發,就接下來再寫。由于理解的不同,可能有寫得不好的,所以有錯誤的地方請指正。
新聞熱點
疑難解答