事件总线 - vue.js中,使用event bus不能更新视图

查看:399
本文介绍了事件总线 - vue.js中,使用event bus不能更新视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

BusA.vue

<template>
  <div>
    <h1>我是BusA组件</h1>
    <div>{{msg}}</div>
    <input type='text' v-model="msg">
  </div>
</template>

<script type="text/ecmascript-6">
  import bus from '../Bus'

  export default{
    data () {
      return {
        msg: 'Hello World!'
      }
    },
    mounted () {
      bus.$on('setMsg', function (content) {
        this.msg = content
        console.log('msg=' + this.msg)
      })
    }
  }
</script>

BusB.vue

<template>
  <div>
    <h1>我是BusB组件</h1>
    <button @click="sendEvent">Say Hi</button>
  </div>
</template>

<script type="text/ecmascript-6">
  import bus from '../Bus'
  export default{
    methods: {
      sendEvent: function () {
        bus.$emit('setMsg', 'Hi Vue!')
      }
    }
  }
</script>

BusA监听到了BusB中触发的事件,并且BusA中能够打印出msg

问题:为什么BusA中视图没有更新?

解决方案

<script type="text/ecmascript-6">
  import bus from '../Bus'

  export default{
    data () {
      return {
        msg: 'Hello World!'
      }
    },
    mounted () {
      bus.$on('setMsg', function (content) {
        this.msg = content  //这里this的指向不正确
        console.log('msg=' + this.msg)
      })
    }
  }
</script>

这篇关于事件总线 - vue.js中,使用event bus不能更新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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