使用Vue也有很长一段时间,但是一直以来都没对其组件之间的通信做一个总结,这次就借此总结一下。
父子组件之间的通信
1)props和$emit
父组件通过props将数据下发给props,子组件通过$emit来触发自定义事件来通知父组件进行相应的操作
具体代码如下:
``` // 父组件 <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: 父实例,如果当前实例有的话
vm.$children: 获取当前实例的直接直接子组件,需要注意的是$children并不保证顺序,也不是响应式的
具体代码如下:
``` // 父组件的代码 <template> <div> <h3>{{title}}</h3> <button @click="amend">在父组件中修改子组件的标题</button> <Children /> </div> </template> <script> import Children from './children.vue'; export default { data() { return { title: '父组件' } }, components: { Children }, methods: { amend() { this.$children[0].title = '修改后的子组件标题'; } } } </script> // 子组件的代码 <template> <div> <h3>{{title}}</h3> <button @click="amend">在子组件中修改父组件的标题</button> </div> </template> <script> export default { data() { return { title: '子组件' } }, methods: { amend() { this.$parent.title = '修改后的父组件标题'; } } } </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> 标题:<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> ```
新闻热点
疑难解答
图片精选