Vue 父子组件和兄弟组件通信

2019-03-08  本文已影响0人  CNSTT

组件通信总结

父传子:props: [args]
子传父:this.$emit(event, args)
兄传弟:vm.$on(event, function (data) {}

Foo.vue 父组件

<template>
  <div class="tmpl">
    <h1>父子组件与兄弟组件通信</h1>
    <h3>子组件通信为 {{childMsg}}</h3>
    <my-bar :message="parentMsg" v-on:showMsg="getMsg"></my-bar>
    <my-baz></my-baz>
  </div>
</template>

<script>
import MyBar from '@/components/Foo/Bar.vue'
import MyBaz from '@/components/Foo/Baz.vue'
export default {
  name: 'Foo',
  components: {
    MyBar, MyBaz
  },
  data () {
    return {
      parentMsg: 'abc123',
      childMsg: ''
    }
  },
  methods: {
    getMsg: function (data) {
      this.childMsg = data
    }
  }
}
</script>

<style scoped>
h1 {
  font-weight: normal;
}
</style>

Bar.vue 子组件(兄)

<template>
  <div class="tmpl">
    <h1>父组件传值为 {{message}}</h1>
    <input type="text" placeholder="请输入子组件内容" v-model="param">
    <button @click="sendParam">通信父组件</button>
  </div>
</template>

<script>
import EventHandler from '@/assets/js/EventHandler.js'
export default {
  name: 'Bar',
  props: {
    message: {
      type: String,
      default: '默认为空'
    }
  },
  data () {
    return {
      param: ''
    }
  },
  methods: {
    sendParam: function () {
      var param = this.param
      this.$emit('showMsg', param)
      EventHandler.$emit('showMsg', param)
    }
  }
}
</script>

<style scoped>
h1 {
  font-weight: normal;
}
.tmpl {
  border: 1px solid #333;
  padding: 30px;
}
</style>

Baz.vue 子组件(弟)

<template>
  <div class="tmpl">
    <h1>Baz</h1>
    <h1>兄弟组件通信为{{brotherMsg}}</h1>
  </div>
</template>

<script>
import EventHandler from '@/assets/js/EventHandler.js'
export default {
  name: 'Baz',
  mounted () {
    var that = this
    EventHandler.$on('showMsg', function (data) {
      that.brotherMsg = data
    })
  },
  data () {
    return {
      brotherMsg: ''
    }
  }
}
</script>

<style scoped>
h1 {
  font-weight: normal;
}
</style>

EventHandler.js 用于兄弟组件之间传递事件

import Vue from 'Vue'
export default new Vue()
image.png
点击按钮后通信

谢谢阅读,有帮助的点个❤!

上一篇 下一篇

猜你喜欢

热点阅读