java做網(wǎng)站沒有php好嗎360瀏覽器網(wǎng)頁版入口
1. 自定義事件
除了可以處理原生的DOM事件, v-on指令也可以處理組件內(nèi)部觸發(fā)的自定義的事件,調(diào)用this.$emit()
函數(shù)就可以觸發(fā)一個自定義事件
$emit()
觸發(fā)事件函數(shù)接受一個自定義事件的事件名以及其他任何給事件函數(shù)傳遞的參數(shù). 然后就可以在組件上使用v-on
來綁定這個自定義事件
{methods: {handleClick(){this.clicks++this.$emit("count",this.clicks )}}
}
所以我們就可以利用自定事件來處理子組件觸發(fā)父組件數(shù)據(jù)的更改和向父組件傳值
2. 子組件觸發(fā)父組件數(shù)據(jù)的改變
通過父組件向子組件傳值的學(xué)習(xí),我們已經(jīng)知道了Vue是單向下行數(shù)據(jù)流, 子組件更改props
中的數(shù)據(jù)不會觸發(fā)父組件數(shù)據(jù)的改變, 但是由于響應(yīng)式原理,父組件數(shù)據(jù)的改變會導(dǎo)致子組件props
中值的改變
那么我們怎樣才能在子組件中改變顯示的結(jié)果呢.
思路:
- 子組件中沒法更改父組件中的數(shù)據(jù),那么我們就讓父組件自己的函數(shù)改自己的數(shù)據(jù)
- 如何在子組件中觸發(fā)父組件中的函數(shù)呢, 就可以通過自定義事件
- 子組件在函數(shù)中觸發(fā)自定義事件, 將父組件中更改數(shù)據(jù)的函數(shù)綁定為自定義事件的函數(shù)
- 然后父組件中的數(shù)據(jù)一變,因為響應(yīng)式,所以子組件中的數(shù)據(jù)會自動改變
示例代碼如下:
<div id="app"><!-- 使用組件 --><!-- 3.在子組件中綁定自定義事件, 將父組件的方法綁定為自定義事件的處理函數(shù)--><my-component :clicks="clicks" @count="handleParentClick"></my-component></div><!-- 組件模板 -->
<template id="MyComponent"><div>被點擊了{{clicks}}次<!-- 1. 子組件通過原生click事件觸發(fā)子組件自己的函數(shù) --><button @click="handleClick">點擊</button></div>
</template><script>// 組件選項對象let MyComponent = {props:["clicks"],template: `#MyComponent`,methods:{handleClick(){// 2.子組件函數(shù)中觸發(fā)自定義事件this.$emit("count")}}}// 實例中注冊組件const vm = new Vue({el:"#app",data: {clicks:0},components: {"MyComponent": MyComponent},methods:{handleParentClick(){// 4. 在父組件函數(shù)中修改父組件中的數(shù)據(jù)this.clicks++}}})
</script>
示例結(jié)果
最后父組件數(shù)據(jù)一變,子組件顯示結(jié)果自然變化
我們也知道$emit
方法在觸發(fā)自定義事件的時候,還可以給自定義事件傳參, 這樣就可以實現(xiàn)子組件向父組件傳參
3. 子組件向父組件傳參
上一小節(jié),我們是在子組件中通過自定義事件觸發(fā)父組件中的函數(shù), 在父組件中修改數(shù)據(jù),
同樣我們也可以在子組件中修改數(shù)據(jù),然后將修改后的數(shù)據(jù)通過自定義事件傳參的方式,傳遞給父組件函數(shù),在父組件函數(shù)中直接用子組件傳過來修改后的數(shù)據(jù)直接替換父組件中的數(shù)據(jù)
示例代碼如下:
<div id="app"><!-- 使用組件 --><!-- 3.在子組件中綁定自定義事件, 將父組件的方法綁定為自定義事件的處理函數(shù)--><my-component :clicks="clicks" @count="handleParentClick"></my-component>
</div><!-- 組件模板 -->
<template id="MyComponent"><div>被點擊了{{clicks}}次<!-- 1. 子組件通過原生click事件觸發(fā)子組件自己的函數(shù) --><button @click="handleClick">點擊</button></div>
</template><script>// 組件選項對象let MyComponent = {props:["clicks"],template: `#MyComponent`,data(){return {count: this.clicks}},methods:{handleClick(){// 2.子子組件函數(shù)中觸發(fā)自定義事件// 2.1 在觸發(fā)自定義事件的時候向自定事件傳參this.count+=2this.$emit("count",this.count)}}}// 實例中注冊組件const vm = new Vue({el:"#app",data: {clicks:0},components: {"MyComponent": MyComponent},methods:{handleParentClick(count){// 4. 在父組件函數(shù)中修改父組件中的數(shù)據(jù)// 4.1 接受自定義事件觸發(fā)時傳遞的參數(shù)console.log(count)this.clicks = count}}})</script>