在使用VUE的事件总线时,数据已经能够成功传递了,但是无法将其修改到data数据中,传递的数据只能在$on中使用
这是uniapp中使用的代码,这是传值的组件(非父子组件),当点击跳转的时候,通过sendMsg方法传值,值是可以传过去的
<navigator :url="'/pages/test/test'" @click="sendMsg(article.path)">
这是methods中定义的sendMsg方法
sendMsg(path){
this.path = path
this.$bus.$emit('sendMsg',path)
}
接着在需要被传值的组件中的mounted中进行接收
mounted() {
this.$bus.$on('sendMsg',(data)=>{
this.path = data
console.log(data)
})
},
data成功打印
如果想加上对data中数据的修改也是可以的
mounted() {
this.$bus.$on('sendMsg',(data)=>{
this.path = data
console.log(data)
console.log(this.path)
})
},
此时在$on中打印this.path值为data
但是data值并不会做更改并显示到页面中
##需要被传值的组件代码
<template>
<view>
<text>{{path}}</text>
</view>
</template>
<script>
export default {
name:'test',
data() {
return {
path:'asfas'
}
},
created(){
this.$bus.$off('sendMsg')
},
mounted() {
this.$bus.$on('sendMsg',(data)=>{
this.path = data
console.log(data)
console.log(this.path)
})
},
methods:{
}
}
</script>
试过将this.path值传递给data
this.path值能成功传递
请问要如何在点击之后传值并且实时更新插值表达式,也就是data中path的数据?
没看出啥毛病,先把这个注释掉看看?
created(){
//this.$bus.$off('sendMsg')
},
思路走死了。你的事件是在挂载完成后调用!!所以得到了传过来的数据,按照需要,你修改了数据后,他第二次传入给这边页面,你需要监听后再来触发事件获取
watch: {
sendMsg: {
handler(newval, oldval) { //新值 旧值 由于是第一次传,所以不存在旧值,故你会打印oldval报出undefind
if (newval != oldval) {//这里对比 前后事件总线传入的数据是否有所出入 这里一般是传入,当前时间, 谁要改数据,谁就传当前时间
//时间在第二次被更改后,变作旧数据 oldval 发现时间不一致 调用
this.$bus.$off('sendMsg')
}
}
}
}
这里估计还有点小问题。但大致意思就是这样,希望对你有所帮助