vue组件之间通信方式实例总结【8种方式】(2)

Vue.component('child',{ inject:['for'],//得到父组件传递过来的数据 data(){ return { mymessage:this.for } }, template:` <div> <input type="tet" v-model="mymessage"> </div> }) Vue.component('parent',{ template:` <div> <p>this is parent compoent!</p> <child></child> </div> `, provide:{ for:'test' }, data(){ return { message:'hello' } } }) var app=new Vue({ el:'#app', template:` <div> <parent></parent> </div> ` })

5. v-model

父组件通过v-model传递值给子组件时,会自动传递一个value的prop属性,在子组件中通过this.$emit(‘input',val)自动修改v-model绑定的值

Vue.component('child',{ props:{ value:String, //v-model会自动传递一个字段为value的prop属性 }, data(){ return { mymessage:this.value } }, methods:{ changeValue(){ this.$emit('input',this.mymessage);//通过如此调用可以改变父组件上v-model绑定的值 } }, template:` <div> <input type="text" v-model="mymessage" @change="changeValue"> </div> }) Vue.component('parent',{ template:` <div> <p>this is parent compoent!</p> <p>{{message}}</p> <child v-model="message"></child> </div> `, data(){ return { message:'hello' } } }) var app=new Vue({ el:'#app', template:` <div> <parent></parent> </div> ` })

6. $parent和$children

Vue.component('child',{ props:{ value:String, //v-model会自动传递一个字段为value的prop属性 }, data(){ return { mymessage:this.value } }, methods:{ changeValue(){ this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值 } }, template:` <div> <input type="text" v-model="mymessage" @change="changeValue"> </div> }) Vue.component('parent',{ template:` <div> <p>this is parent compoent!</p> <button @click="changeChildValue">test</button > <child></child> </div> `, methods:{ changeChildValue(){ this.$children[0].mymessage = 'hello'; } }, data(){ return { message:'hello' } } }) var app=new Vue({ el:'#app', template:` <div> <parent></parent> </div> ` })

7. boradcast和dispatch

vue1.0中提供了这种方式,但vue2.0中没有,但很多开源软件都自己封装了这种方式,比如min ui、element ui和iview等。

比如如下代码,一般都作为一个mixins去使用, broadcast是向特定的父组件,触发事件,dispatch是向特定的子组件触发事件,本质上这种方式还是on和on和emit的封装,但在一些基础组件中却很实用。

function broadcast(componentName, eventName, params) { this.$children.forEach(child => { var name = child.$options.componentName; if (name === componentName) { child.$emit.apply(child, [eventName].concat(params)); } else { broadcast.apply(child, [componentName, eventName].concat(params)); } }); } export default { methods: { dispatch(componentName, eventName, params) { var parent = this.$parent; var name = parent.$options.componentName; while (parent && (!name || name !== componentName)) { parent = parent.$parent; if (parent) { name = parent.$options.componentName; } } if (parent) { parent.$emit.apply(parent, [eventName].concat(params)); } }, broadcast(componentName, eventName, params) { broadcast.call(this, componentName, eventName, params); } } };

8. vuex处理组件之间的数据交互

如果业务逻辑复杂,很多组件之间需要同时处理一些公共的数据,这个时候才有上面这一些方法可能不利于项目的维护,vuex的做法就是将这一些公共的数据抽离出来,然后其他组件就可以对这个公共数据进行读写操作,这样达到了解耦的目的。

详情可参考:https://vuex.vuejs.org/zh-cn/

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ccb1bf21020131bc249f7dc170b7b5a3.html