国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue組件開發(fā)初探

2024-05-06 15:11:36
字體:
供稿:網(wǎng)友

注冊(cè)一個(gè)組件

有兩種方式可以注冊(cè)一個(gè)組件,第一種是全局注冊(cè),第二種是局部注冊(cè)

# 全局注冊(cè)Vue.component('my-component',{  template: '<span>Hello</span>'})# 局部注冊(cè)var child = {  template: '<span>Hello</span>'}new Vue({  // ···  components:{    my-component: child  }})

注意:組件的注冊(cè)必須要在Vue實(shí)例創(chuàng)建之前

使用組件

<div id="app">  <my-component></my-component></div>

當(dāng)我們需要使用到data時(shí),data必須是一個(gè)函數(shù),否則將會(huì)報(bào)錯(cuò),這是Vue的一個(gè)規(guī)則,如下

Vue.component('my-component',{  template: '<span>{{message}}</span>',  data:function(){    return {message:'hello'}  }})

組件間消息傳遞

當(dāng)我們封裝了組件A,但是組件A又嵌套了組件B,這時(shí)候組件AB形成了父子組件的關(guān)系,我們應(yīng)該怎么來讓父組件傳遞消息給子組件呢,這里用到了一個(gè)屬性值props,如下

Vue.component('my-component',{  props: ['message']  template: '<span>{{message}}</span>'})# 通過props傳遞消息給子組件<my-component message="Hello"></my-component>

上面的例子,我們通過props傳遞了參數(shù)給子組件,確實(shí)能改變子組件的值,但是,假如我們有這樣一個(gè)要求,props的值是動(dòng)態(tài)改變的,那么這種靜態(tài)字面量傳遞參數(shù)的方式就不能滿足我們的需求了。如下將說明如何進(jìn)行動(dòng)態(tài)的props值設(shè)定

<div id="app">  <input v-model="parentMsg"><br>  <my-component v-bind:message="parentMsg"></div>

這里通過v-bind的命令,將我們的message與parentMsg進(jìn)行綁定,這樣,當(dāng)我們的parentMsg改變時(shí),message將能實(shí)時(shí)改變

自定義事件

父子組件之間如果通過props來傳遞數(shù)據(jù)的話,那么似乎只能進(jìn)行單向的數(shù)據(jù)傳遞,只能從父組件向子組件傳遞,假如我們需要從子組件傳遞消息回去,那么就需要用到自定義事件了

# 使用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>

這里,我們點(diǎn)擊按鈕,按鈕的顯示的數(shù)值將會(huì)改變,同時(shí),total的值也會(huì)動(dòng)態(tài)的改變,這就是子組件回傳數(shù)據(jù)的實(shí)例,我們點(diǎn)擊按鈕時(shí),將會(huì)首先執(zhí)行button的onclick方法,在onclick方法里面,通過this.$emit('increment')來執(zhí)行我們自定義的事件,假如我們需要在$emit中添加參數(shù),那么我們就要在$on()中進(jìn)行回調(diào)的處理

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 米易县| 定日县| 邵武市| 永修县| 安陆市| 泗阳县| 福海县| 松溪县| 周宁县| 石楼县| 晋城| 鄂托克旗| 讷河市| 沅陵县| 禹城市| 宁国市| 前郭尔| 军事| 龙里县| 大安市| 碌曲县| 望城县| 阜新| 新蔡县| 察哈| 高邑县| 永清县| 苏尼特右旗| 诸暨市| 广饶县| 海阳市| 乌审旗| 沐川县| 山丹县| 保山市| 松江区| 太康县| 叙永县| 南充市| 福泉市| 观塘区|