美文网首页
复习组件间值传递(兄弟组件传递)

复习组件间值传递(兄弟组件传递)

作者: Do_Du | 来源:发表于2019-11-29 16:15 被阅读0次

利用中转站新建bus.js文件实现

$emit('事件名',要传递的值) :通过bus发送数据

$on('事件名',回调函数会接收所有传入事件触发函数):通过bus接收数据

1、新建一个bus.js文件作为兄弟组件间传值的中转站

import Vue from 'vue'

export default new Vue;

2、父组件调用2个子组件

<template>
  <div class="big">
    <Son1 />
    <Son2 />
  </div>
</template>

<script>
import Son1 from './Son1'
import Son2 from './Son2'
export default {
  name: 'Home',
  components: {
    Son1,
    Son2
  },
  data() {
    return {
    }
  },
}
</script>

3、子组件1:引入中转bus.js文件;触发事件时传递值出去给BUS中转站

<template>
  <div class="big">
    <div @click="clickSon">子组件一号,点我传值,再点消失</div>
  </div>
</template>

<script>
import Bus from '../../assets/js/index'
export default {
  name: 'Son1',
  data() {
    return {
      son1Message: {
        isShow: true,
        info: '我是来自一号组件的大魔王阿星!'
      }
    }
  },
  created() {
  },
  methods: {
    clickSon() {
      this.son1Message.isShow = !this.son1Message.isShow
      Bus.$emit('aaa', this.son1Message)
    }
  }
}
</script>

4、子组件2: 引入中转bus.js文件;接收子组件1传递来的值并接收变量渲染到页面

<template>
  <div class="son2">
    子组件二号
    <div v-if="isShow">{{ son2Message }}</div>
  </div>
</template>

<script>
import Bus from '../../assets/js/index'
export default {
  name: 'Son2',
  components: {
  },
  data() {
    return {
      isShow: '',
      son2Message: ''
    }
  },
  created() {
    Bus.$on('aaa', res => {
      this.isShow = res.isShow
      this.son2Message = res.info
    })
  },
  methods: {
  }
}
</script>

相关文章

网友评论

      本文标题:复习组件间值传递(兄弟组件传递)

      本文链接:https://www.haomeiwen.com/subject/zrsgwctx.html