您如何eventBus总线以传达更新到Vue组件中的视图? [英] How do you eventBus a bus to communicate updates to a view in a Vue component?

查看:86
本文介绍了您如何eventBus总线以传达更新到Vue组件中的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Listen for custom events for the bus in component b. However, after dispatching events in component a, it accesses component b. the listening function of component b is executed, but msg of data function is not updated

请不要说 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',但这没有用.

I tried using 'watch' to observe 'msg', but it didn't work.

你能帮我吗?

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

If possible, I would like to deeply understand 'bus'

推荐答案

仅当您在发射时页面中同时存在组件A和组件B时,此方法才有效.从代码中可以看出,您正在从组件A发出值,然后导航到组件B并在其中期待该值.

This will work only if both component A and component B are present in the page at the time you are emitting. From the code it seems that you are emitting the value from component A and then navigating to component B and expecting the value there.

您正在做的事情就像踢一个球,然后追着它跑,然后捡起来却发现球已经消失了.您需要的是另一个已经在场的人来接球.

What you are doing is something like kicking a ball and then running after it and then picking it only to find that the ball has disappeared. What you need is another person already present at that location who picks up the ball.

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

A solution in this case can be to set the value in localstorage, navigate to the other route and then read the value from localstorage.

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

If the value you need to pass is a simple value, you can just pass it in query string and then read from $router params in component B.

这篇关于您如何eventBus总线以传达更新到Vue组件中的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆