Web前端之路让前端飞Vue.js开发技巧

非兄弟非父子组件bus通讯踩坑记录

2017-10-24  本文已影响191人  ishowman

FBI Warning:本文是记录本菜鸟学习bus通信的一次记录。如大佬熟练掌握Vue或已对Vue源码有了解,不建议浪费时间阅读。部分文字可能引起感官上的不适,请在男/女朋友的陪同下阅读

1.整体思路

看了官网文档关于bus的用法,遂想写个简单的组件bus通讯demo练手。

2. 相关代码

上面的思路对应代码如下。为方便直接用vue-cli构建

2.1 showTime.vue

<template>
  <div >
    <p>时间:{{time}}</p>
  </div>
</template>
<script>
import bus from './bus'
export default {
  data () {
    return {
      time: '初始值'
    }
  },
  created() {
    bus.$on('get', data => { 
      console.log(data)
      this.time= data
    })
  }
}
</script>

2.2 getTime.vue

<template>
  <div>
      <p>我是组件b</p>
      <button @click="getTime">发送时间给组件a</button>
  </div>
</template>
<script>
import bus from './bus'
export default {
    methods: {
        getTime() {
            bus.$emit('get', `${new Date()}`)
        }
    }
}
</script>

2.3 bus.js

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

2.4 路由

import Vue from 'vue'
import Router from 'vue-router'
import getTime from '@/components/getTime '
import showTime from '@/components/showTime'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/',
      component: showTime 
    },
    {
      path: '/getTime',
      component: getTime 
    }
  ]
})

3. 出现问题

3.1 操作步骤

3.2 问题概述

4. debug思路

    bus.$on('get', data => { 
      console.log(data)
      this.time= data
    })
    console.log(bus._events)  // 

5. 解决方案

上一篇 下一篇

猜你喜欢

热点阅读