非父子组件的传组问题
vue
it书童
2020-01-08 22:31:53
0赞
0踩
729阅读
0评论
一个页面可以细化拆分成不同的组件
父子组件间可以用属性和事件通信,如果是跨层传递,能借助中间层进行通信,但这种方式太麻烦;而且如果是同级或者没有层级关系,要怎么传值?
有两种方案:
- vuex
- 发布订阅 也称总线
本文以发布订阅为例:
在 Vue 的实例挂载一个 bus 属性,这样在每一次 vue 实例都有这个属性
<div id="app">
<div class="container mt-5">
<child content="Dell"></child>
<child content="Lee"></child>
</div>
</div>
<script>
// 在 Vue 的实例挂载一个 bus 属性,这样在每一次 vue 实例都有这个属性
Vue.prototype.bus = new Vue()
Vue.component('child', {
// 接收父组件传过来的值
data: function() {
return {
selfContent: this.content
}
},
props: {
content: String
},
template: '<div @click="handleClick">{{ selfContent }}</div>',
methods: {
handleClick: function() {
// 将事件传递给总线
this.bus.$emit('change', this.selfContent)
}
},
mounted: function() {
// 回调函数的 this 会被改变,提前承接此变量
var this_ = this
this.bus.$on('change', function (msg) {
console.log(msg)
this_.selfContent = msg
})
}
})
var app = new Vue({
el: '#app',
methods: {
handleClick: function() {
// 会触发
console.log('自定义事件触发的点击')
}
}
})
</script>
总线为不同层级的组件提供了传递数据的通道
- 上一篇: 给组件绑定原生事件
- 下一篇: 在 Vue 中使用插槽 slot

关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
转载须注明出处:https://www.itshutong.com/articles/381/group-passing-problem-of-non-parent-child-components
精品付费
个人开发者通过payjs接入微信支付
2582
0
这一次,真正掌握composer
1509
0
相关推荐
第一个vue实例与MVVM
378
0
vue基础指令 v-once和v-pre
560
0
v-text 与 v-html
503
0
vue 路由组件
498
0
模板语法-插值
477
0
vue 组件基本使用
484
0
vue 组件参数校验与非 props 特性
540
0
vue 中的作用域插槽
512
0
使用 animate 动画库
504
0
vue 同时使用过渡和动画
554
0