我们知道vue的精华就在于组件话开发,第一次看vue的时候懵懵懂懂,只是大概了解了怎么去用。今天闲来无事第二次去看发现了很多精华的东西,现在写出来与大家分享下。
vue的组件间通信一般分为父子组件通信和兄弟组件通信。父子组件通信是一层一层向下传递prop然后一层层通过事件向上传递。而兄弟组件之间通信一般通过vuex进行,在本文中就不多赘述。
单向数据流
这是父子组件的核心概念,prop是单向绑定的。当父组件的属性发生变化的时候,会传导到子组件。但是反之,为了防止子组件无意间修改来父组件的状态,从下往上的数据流是不允许的。
下面我们举个栗子:



当父组件属性改变时,会传导进子组件。而子组件的属性改变时,会报错。
那么如果是不是局的props有点鸡肋了,只能初始化组件的时候用,在子组件内并不能进行操作。
其实还是用两种办法去操作props的:
1.定义一个局部变量,并用props初始化它,以后操作这个局部变量。

当我们将0传入子组件时,然后点击按钮看一下变化。

2.定义一个计算属性,处理prop的值并返回。


自定义事件
了解了组件对单向数据流,我们知道了组件从上至下是通过prop传递进行通信的。那从下往上怎么办呢?vue规定子组件通过触发事件来与父组件进行通信。即父组件在调用子组件时,定义事件,子组件通过触发这个事件来与父组件进行通信。
父组件通过v-on:eventName="parentEventName"来设置监听,子组件通过$.emit('eventName')来触发事件。


我们给子组件绑定来trigger事件,事件源是父组件的myClick事件,并调用来child子组件两次。而子组件child中的按钮被点击时,子组件add事件触发,将自身的count++,且触发letrigger事件将父组件内的total++。

而且更奇妙的是,子组件触发事件时可以使用载荷(payload)。让我们来修改下demo


我们通过子组件触发父组件的事件,将子组件input的内容发送给父组件。

当然,有时候我们想给子组件的根元素绑定原生事件,此时可以使用修饰符.native来进行操作。


此时我们给子元素绑定原生点击事件,来监测鼠标的点击位置。

.sync修饰符
单向数据绑定可以防止子组件无意间去窜改父组件的状态,双向数据绑定在一定的场景下也是有一定用处的。比如在开发可复用的组件库时,双向数据绑定显得十分有用。
.sync修饰符帮我们做到来这一点,在vue2.0中.sync被移除了,在vue2.3.0又被重新引入,只是做了很大的修改。.sync现在作为一个语法糖来使用,他会被扩展为一个自动更新父组件属性的v-on监听器。
总结一下就是.sync只是在底层自动为子组件绑定来一个监听事件,子组件只需要在需要修改父组件状态时去手动触发他就OK了。
例如:

会被扩展为:

是不是很眼熟,它只是将bar的值绑定在了child上,同时给child绑定了一个update:foo的监听事件。相对应的我们只需要在子组件定义foo的prop,然后手动$.emit('update:foo')进行触发就可以了。
多说无益,上个demo


这里我们通过watch变量my_msg来触发事件,更新父组件。

EventBus 实现非父子组件通信
通过实例化一个Vue对象( 比如bus = new Vue() )作为母线,在组件中通过事件将参数传递出去( bus.$emit(event, [...args]) ),然后在其他组件中再通过bus( 这里按照刚前面实例化Vue对象后的叫法 )来监听此事件并接受参数( bus.$on(event, callback) )。
PS: 共用同一个Vue的实例( new Vue() ),通过此实例进行事件传递参数,在其他组件中监听此事件并且接收参数实现通信。
例子
bus.js (实例化一个Vue对象)

组件Hello.vue

组件World.vue

组件Home.vue (同时引入Hello.vue组件和World.vue组件)

效果图展示:

传递参数后:

VUEX实现组件通信
项目中利用 vue的辅助函数传值和取值
新建一个store.js文件

在vue实例中注册store

在App.vue组件中使用mapMutations传参,修改state数据(状态)
要点: 要写在methods下面,因为mapActions/mapMutations只是把action/mutation函数绑定到你的methods里了;你调methods里的方法的时候照常传参就可以了。

再定义一个子组件,获取state对象里面的数据
