最近在看vue的文档 好好学习中 vue中实现通过bus.js实现非父子组件之间的通信 简单明了 ,应用在商城网站上

一般在项目中,有时候我们需要在组件之间通信传值,  直接看代码吧

在实现之前,首先创建一个文件夹utils,  然后写一个文件名为bus.js, 内容如下

import Vue from  'vue'
const bus = new Vue()

export default bus

在index.vue中   

注明: 刚刚发现了一个bug,就是在页面切换回来的时候,值是有问题的,作出新的修改

<template>
    <div class="app">
        首页 <br>
        <button @click="getcount">累加</button>  
        <button @click="setcount">减少</button>  <br>
        数量:  <span>{{count}}</span>
    </div>
</template>
<script>
import bus from '@/utils/bus.js'
    export default {
        data(){
            return{
                count: 0,
            }
        },
        methods: {  //未修改之前的  
            getcount(){
                this.count++
                bus.$emit('count',this.count)  // 发送数据
            },
            setcount(){
                this.count--
                bus.$emit('count',this.count)
            }
        }
methods: { //修改好的代码
            getcount(){
                this.count++
                bus.$emit('count',this.count)  // 发送数据
                localStorage.setItem('count',this.count)
            },
            setcount(){
                this.count--
                bus.$emit('count',this.count)
                localStorage.setItem('count',this.count)
            }
        },
        created(){
            this.count = localStorage.getItem('count')
        }

    }
</script>

在另一个页面上通过bus.js传过来的值  进行接收并展示  我这次的是在APP.vue上得  

在app.vue

<template>
<div class="button_box">
        <div class="button">我的订单</div>
        <div class="button">购物车(<span>{{count}}</span>)</div>
        <div class="button">我的收藏</div>
    </div>
</template>

<script>
import bus from './utils/bus.js'  // 注意 两者都记得引入bus.js
export default {
  name: 'App',
  data(){
    return {
      count: 0
    }
  },
  created(){
    bus.$on('count',value=>{
      // console.log(value)  // 接收传过来的数据
      this.count = value
    })
  }
}
</script>

这样就可以实现传值了 

 效果图:

原文地址:https://www.cnblogs.com/PinkYun/p/10083179.html