vue使用bus进行兄弟组件传值

1.新建bus.js

import Vue from 'vue'
export default  new Vue

2.在需要传值和接受值的vue文件中,各自引入bus.js

import bus from '../util/bus'

3.定义传值的方法,使用bus.$emit('methodName',data), methodName是自定义的方法名

<button @click="trans()">传值</button>
methods: {
    trans(){
      bus.$emit('test',this.helloData)
    }
  },

4.在要接收值的组件里,使用bus.on('methodName',val =>{ }) ,val 就是传过来的值

 mounted(){
    bus.$on('test',val=>{
      console.log(val);
      this.cdata = val
    })
  }

完整例子:

App.vue

<template>
  <div id="app">
     <HelloWorld/>
     <child></child>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld'
import Child from './components/Child'
export default {
  name: 'App',
  components: {
    HelloWorld,Child
  }
}
</script>

bus.js

import Vue from 'vue'
export default  new Vue

子组件HelloWorld.vue

<template>
<div>
<button @click="trans()">传值</button>
</div>
</template>
<script>
import bus from '../util/bus'
export default {
  name: "HelloWorld",
  data () {
    return {
      helloData:"hello"
    };
  },
  methods: {
    trans(){
      bus.$emit('test',this.helloData)
    }
  },
}
</script>

子组件Child.vue

<template>
<div>
{{cdata}}
</div>
</template>
<script>
import bus from '../util/bus'
export default {
  name: "Child",
  data () {
    return {
      cdata:"子数据"
    };
  },
  mounted(){
    bus.$on('test',val=>{
      console.log(val);
      this.cdata = val
    })
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/luguankun/p/11701121.html
今日推荐