使用Vue也有很長(zhǎng)一段時(shí)間,但是一直以來(lái)都沒(méi)對(duì)其組件之間的通信做一個(gè)總結(jié),這次就借此總結(jié)一下。
父子組件之間的通信
1)props和$emit
父組件通過(guò)props將數(shù)據(jù)下發(fā)給props,子組件通過(guò)$emit來(lái)觸發(fā)自定義事件來(lái)通知父組件進(jìn)行相應(yīng)的操作
具體代碼如下:
``` // 父組件 <template> <div> <h3>props和$emit</h3> <Children v-on:changeMsg="changeMsg" :msg="msg"/> </div> </template> <script> import Children from './children'; export default { data() { return { msg: '傳遞的值' } }, components: { Children }, methods: { changeMsg(val) { this.msg = val; } } } </script> // 子組件 <template> <div> <h3 @click="notify">{{msg}}</h3> </div> </template> <script> export default { data(){ return { } }, props: ['msg'], methods: { notify() { this.$emit('changeMsg', '修改后的'); } } } </script> ```2)vm.$parent和vm.$children
vm.$parent: 父實(shí)例,如果當(dāng)前實(shí)例有的話(huà)
vm.$children: 獲取當(dāng)前實(shí)例的直接直接子組件,需要注意的是$children并不保證順序,也不是響應(yīng)式的
具體代碼如下:
``` // 父組件的代碼 <template> <div> <h3>{{title}}</h3> <button @click="amend">在父組件中修改子組件的標(biāo)題</button> <Children /> </div> </template> <script> import Children from './children.vue'; export default { data() { return { title: '父組件' } }, components: { Children }, methods: { amend() { this.$children[0].title = '修改后的子組件標(biāo)題'; } } } </script> // 子組件的代碼 <template> <div> <h3>{{title}}</h3> <button @click="amend">在子組件中修改父組件的標(biāo)題</button> </div> </template> <script> export default { data() { return { title: '子組件' } }, methods: { amend() { this.$parent.title = '修改后的父組件標(biāo)題'; } } } </script> ```3)自定義事件的v-model
https://cn.vuejs.org/v2/guide/components-custom-events.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6%E7%9A%84-v-model
具體代碼如下:
``` // 父組件 <template> <div> 標(biāo)題:<input type="text" v-model="mymessage"><br /> <Children v-model="mymessage" /> </div> </template> <script> import Children from './children.vue'; export default { data() { return { mymessage: '名字', } }, components: { Children } } </script> // 子組件 <template> <div> <input type="text" :value="mymessage" @input="changeValue"> </div> </template> <script> export default { model: { prop: 'mymessage', event: 'input' }, props: ['mymessage'], methods: { changeValue(event){ this.$emit('input', event.target.value); } } } </script> ```
新聞熱點(diǎn)
疑難解答
圖片精選