当前位置: 移动技术网 > IT编程>网页制作>CSS > vue.js组件之组件通信

vue.js组件之组件通信

2019年01月15日  | 移动技术网IT编程  | 我要评论

vue.js——组件通信

组件关系有:父子组件通信、兄弟组件通信、跨级组件通信。

一、自定义事件

\

子组件用$emit()来触发事件,父组件用$on()来监听子组件的事件。

父组件也可以直接在子组件的自定义标签上使用v-on来监听子组件出发的自定义事件。


总数:{{ total }}

<script> vue.component('my-component',{ template:'\

\ \ \

', data:function () { return{ counter:0 } }, methods:{ handleincrease:function () { this.counter++; this.$emit('increase',this.counter); }, handlereduce:function () { this.counter--; this.$emit('reduce',this.counter); } } }); var app = new vue({ el:'#app', data:{ total:0 }, methods:{ handlegettotal:function (total) { this.total = total; } } }) </script>

子组件有两个按钮实现效果,改变组件的data"counter"后,通过$emit()再把它传递给父组件,父组件用绑定的两个方法。

除了用v-on在组件监听自定义事件外,也可以监听dom事件,这时可以用.native修饰符表示监听的是一个原声的事件,监听的是该组件的根元素。

使用v-model


总数为:{{ total }}

<script> vue.component('my-component',{ template:'', data:function () { return { counter:0 } }, methods:{ handleclick:function () { this.counter++; this.$emit('input',this.counter); } } }); var app = new vue({ el:'#app', data:{ total:0 } }) </script>

$emit的事件名为特殊的inpuut,在使用组件的父级,并没有在上使用@input=“handle”,而是直接用v-model绑定的一个数据total。v-model还可以用来创建自定义的表单输入组件。


总数为:{{ total }}

<script> vue.component('my-component',{ props:['value'], template:'', methods:{ updatevalue:function (event) { this.$emit('input',this.target.value); } } }); var app = new vue({ el:'#app', data:{ total:'', }, methods:{ handlereduce:function () { this.total--; } } }) </script>

非父子组件通信

在vue.js 2.x中,推荐使用一个空的vue实例作为中央事件总线。


{{ message }}

<script> var bus = new vue(); vue.component('component-a',{ template:'', methods:{ handleevent:function () { bus.$emit('on-message','来自组件component-a的内容'); } } }) var app = new vue({ el:'#app', data:{ message:'' }, mounted:function () { var _this = this; bus.$on('on-message',function (msg) { _this.message = msg; }) } }) </script>

首先创建了一个名为bus的空的vue实例,全局定义了组件component-a,在app初始化时,在生命周期mounted钩子函数里监听来自bus的事件on-message,在组件component-a中,点击按钮会通过bus把事件发出去,此时app就会就接收到来自bus的事件,进而在回掉里完成自己的业务。还有两种方式实现组件间的通信:父链和子组件。不建议用父链操作。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网