vue2 基础学习05 (Vue组件:非父子组件之间的通信)

6次阅读

共计 1698 个字符,预计需要花费 5 分钟才能阅读完成。

前言
我将要实现的是:点击按钮,将组件 2 中的数据传递给组件 1,在组件 1 中展示。

源代码
可以直接复制执行
<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<title> 非父子组件中的通信 </title>
<!– 开发环境版本,包含了有帮助的命令行警告 –>
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>
</head>
<style>
.componentOne {
background-color: greenyellow;
border: 1px solid green;
width: 250px;
height: 80px;
margin-left: 20px
}

.componentTwo {
background-color: lightgray;
border: 1px solid green;
width: 250px;
height: 80px;
margin-left: 20px
}
</style>

<body>
<div id=”app”>
<component-one></component-one>
<component-two></component-two>
</div>

<script>
// 在 vue 上面挂载一个 $bus 作为中央处理组件
Vue.prototype.$bus = new Vue()

// 组件 1
var componentOne = {
template: ‘<div class=”componentOne”> 组件 1 — {{fromtwo}}</div>’,
data() {
return {
onemsg: ‘ 我是组件 1 的数据 ’,
fromtwo: ” // 接受从组件 2 传过来的数据
}
},
created() {
//1. 这是方法一
/*var self = this // 先接受 这个实例中的 this
this.$bus.$on(‘sending’,function(val){
//this.fromtwo = val // 这里不了可以这样写,因为在这个作用域中,this 代表的是 $bus 中
self.fromtwo = val // 这里的
})*/

//2. 也可以直接用箭头函数

this.$bus.$on(‘sending’, (val) => {// 箭头函数改变了 this 的指向
this.fromtwo = val
})
},
}
// 组件 2
var componentTwo = {
template: `<div class=”componentTwo”>
组件 2
<button @click=”toOne”> 我要将我的数据传给组件 1 </button>
</div>`,
data() {
return {
twomsg: ‘ 我是组件 2 的数据 ’,
}
},
methods: {
toOne() {
this.$bus.$emit(‘sending’, this.twomsg)
}
},
}

new Vue({
el: ‘#app’,
// 声明组件
components: {
‘component-one’: componentOne,
‘component-two’: componentTwo,
}
})
</script>
</body>

</html>

演示

总结步骤

创建一个空实例(bus 中央事件总线也可以叫中间组件)

利用 $emit $on 的触发和监听事件实现非父子组件的通信
Vue.prototype.$bus=new Vue()// 在 vue 上面挂载一个 $bus 作为中央处理组件
this.$bus.$emit(‘ 自定义事件名 ’,’ 传递的数据 ’)// 触发自定义事件传递数据
this.$bus.$on(‘ 自定义事件名 ’,fn)// 监听自定义事件获取数据

从网上了解到,解决的方案还有 vuex、provide/inject 是解决同根往下派发、本地存储也可以进行非父子组件之间的通信
这块暂时没学到,待学习。

正文完
 0