转载于https://blog.csdn.net/weixin_44096448/article/details/102739414
1.建⽴⼀个公共的js⽂件,专⻔⽤来传递消息。bus.js
import Vue from 'vue' export default new Vue
2.在需要传递的两个组件中都引入bus.js
import bus from '../util/bus.js'
3.定义一个方法传递msg
<button @click="go">传递消息</button>
methods: { go() { bus.$emit('msg',this.msg) } }
4.在接收消息的组件中使用bus.$on或bus.$emit接收消息
mounted () { bus.$on('msg', (val) => { this.uName = val }); }
5.代码如下:
-
<template>
-
<div>
-
<h3>
-
我是:{{msg }}
-
<button @click="go">传递消息
</button>
-
<test2>
</test2>
-
</h3>
-
</div>
-
</template>
-
-
<script>
-
import bus
from
'../util/bus.js'
-
import test2
from
'@/views/test2'
-
export
default {
-
name:
"test1",
-
components: {
-
test2
-
},
-
data() {
-
return {
-
msg:
'小明'
-
}
-
},
-
methods: {
-
go() {
-
bus.$emit(
'msg',
this.msg)
-
}
-
}
-
}
-
</script>
-
-
<style scoped>
-
-
</style>
-
<template>
-
<div>
-
<h3 v-if="uName !== ''">你好啊!{{uName}}
</h3>
-
</div>
-
</template>
-
-
<script>
-
import bus
from
'../util/bus.js'
-
export
default {
-
name:
"test2",
-
data() {
-
return {
-
uName:
''
-
}
-
},
-
mounted () {
-
bus.$on(
'msg',
(val) => {
-
this.uName = val
-
});
-
}
-
}
-
</script>
-
-
<style scoped>
-
-
</style>