您如何通过事件总线来向Vue组件中的视图传达更新?

问题描述 投票:0回答:1

收听组件b中总线的自定义事件。但是,在组件a中分派事件后,它将访问组件b。已执行组件b的侦听功能,但未更新数据功能的msg

请不要说Vuex

相关代码基于Vue CLi3

此处代码:组件A:

    <template>
      <div>
          Component A
          <button @click="sendMsg">pushB</button>
      </div>
    </template>
    <script>
    import bus from './bus'
    export default {
        methods: {
            sendMsg() {
                bus.$emit('send', 'hello Component B')
                this.$router.push('/bbb')
            }
        }
    }
    </script>

B部分:

<template>
    <div>
        <p>component B:{{ msg }}</p>
    </div>
</template>
<script type="text/javascript">
import  bus  from './bus'
export default {
    data () {
        return {
            msg: 'bbb'
        }
    },
    mounted () {
        bus.$on('send', data => {
            console.log(data)
            console.log(this)
            this.msg = data
        })    
    } 

}
</script>

bus.js

import Vue from 'vue';
export default new Vue()

路由器:

const aaa = () => import('@/components/demo/bus/a')
const bbb = () => import('@/components/demo/bus/b')
export default new Router({
  routes: [{
      path: '/aaa',
      component: aaa
    },
    {
      path: '/bbb',
      component: bbb
    }]
})

[我尝试使用'watch'观察'msg',但没有用。

您能帮我吗?

[如果可能,我想深入了解'公共汽车'

javascript vuejs2 event-handling vue-cli-3 event-bus
1个回答
0
投票

仅当您在发射时页面中同时存在组分A和组分B时,此方法才有效。从代码中看,您似乎是从组件A发出值,然后导航到组件B并在那里期望值。

[您正在做的事情就像踢一个球,然后追它然后捡起来。您需要的是在那个位置接球的另一个人[[已经存在。

在这种情况下,一种解决方案是在localstorage中设置值,导航到另一条路线,然后从localstorage中读取值。

如果您需要传递的值是一个简单值,则可以将其传递给查询字符串,然后从组件B中的$ router参数中读取。

© www.soinside.com 2019 - 2024. All rights reserved.