Vue 组件通信(组件间通信)
2017-12-18 16:00
302 查看
1、中央事件总线bus
2、父链
注:尽量少用,父子组件最好通过props和$emit来通信。
3、子组件索引
注:仅仅作为直接访问子组件的应急方案,避免在模板或者计算属性中使用$refs.
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>Vue</title> </head> <body> <div id="app"> <p>{{message}}</p> <my-component></my-component> </div> <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script> <script type="text/javascript"> var bus = new Vue(); Vue.component('my-component', { template: `<button @click="handleEvent">传递事件</button>`, methods: { handleEvent: function() { bus.$emit('on-message', '来自组件my-component的内容') } } }) new Vue({ el: "#app", data: { message: '' }, mounted: function() { var _this = this; //监听来自bus实例的事件 bus.$on('on-message', function(msg) { _this.message = msg; }) } }) </script> </body> </html>
2、父链
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>Vue</title> </head> <body> <div id="app"> <p>{{message}}</p> <my-component></my-component> </div> <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script> <script type="text/javascript"> Vue.component('my-component', { template: `<button @click="handleEvent">通过父链修改数据</button>`, methods: { handleEvent: function() { this.$parent.message = '来自组件my-component的内容' } } }) new Vue({ el: "#app", data: { message: '' } }) </script> </body> </html>
注:尽量少用,父子组件最好通过props和$emit来通信。
3、子组件索引
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <title>Vue</title> </head> <body> <div id="app"> <button @click="handleRef">获取子组件内容</button> <p>父组件:{{message}}</p> <my-component ref='comA'></my-component> </div> <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script> <script type="text/javascript"> Vue.component('my-component', { template: '<div>子组件</div>', data:function(){ return { message:'子组件内容' } } }); new Vue({ el: "#app", data:{ message:'' }, methods:{ handleRef:function(){ var msg = this.$refs.comA.message; this.message = msg; } } }) </script> </body> </html>
注:仅仅作为直接访问子组件的应急方案,避免在模板或者计算属性中使用$refs.
相关文章推荐
- Vue中父组件向子组件通信的方法
- vue组件间的通信案例
- Vue父子组件通信实践
- Vue2.0 组件通信
- Vue组件间的通信
- Vue2.0基于vue-cli+webpack同级组件之间的通信教程(推荐)
- vue2.0父子组件间通信
- vue路由组件传参-页面通信
- vue2.0--组件通信(非vuex法)
- Vue 父子组件、组件间通信
- 详解Vue组件之间的数据通信实例
- Vue 父子组件、组件间通信
- vue组件之间的通信
- vue 父子组件之间的通信 props
- 【vue】父子组件间通信----传值
- vue组件间通信
- vue中组件之间相互通信(一)
- 使用bus实现Vue组件间通信
- 第十节:实现vue组件之间的通信
- 聊聊Vue.js组件间通信的几种姿势