VUE组件之间多种通信方式

2017-10-27  本文已影响61人  傻瓜也是瓜_

给大家介绍几种VUE组件之间通信的方式,根据业务场景大家可以自行选择。

1、通过$emit让子组件与父通信
/*
 @ 子组件 btn.vue
*/

<template>
    <button @click="trigger">{{text}}</button>
</template>
<script>
  module.exports = {
     data () {
          return {}
     },
     props: {
         text: {
            type: [String, Number],
            default: '确定'
         }
      },
    methods: {
       trigger () {
          //触发一个名字叫‘hello’的自定义事件, 并传递一个叫str的参数
          var str = 'hello word'
          this.$emit('hello', str)
       }
    }
  }
</script>
/*
监听自定义hello事件,并触发helloWord方法
*/
<template>
    <btn @hello="helloWord"></btn>
</template>
<script>
  import btn from 'btn.vue'
  module.exports = {
     data () {
          return {}
     },
    methods: {
       helloWord(str) {
            console.log(str)
        }
    },
    components: { btn }
  }
</script>
2、通过ref获取子组件实例(属性、方法)
/*
 @ 子组件 btn.vue
*/

<template>
    <button @click="trigger">{{text}}</button>
</template>
<script>
  module.exports = {
     data () {
          return {
              text: '确定'
          }
     },
    methods: {
       _init () {
          this.text = 'hello word'
       }
    }
  }
</script>
/*
通过ref与子组件通信
*/
<template>
    <btn ref="btn"></btn>
</template>
<script>
  import btn from 'btn.vue'
  module.exports = {
     data () {
          return {}
     },
     created () {
        //获取btn实例  
       var vueBtn =  this.$refs.btn
        
        //调用_init方法
        vueBtn._init()
    },
    components: { btn }
  }
</script>
2、通过一个空的VUE实例作为事件总代理,父与子、子与父、兄弟组件之间就可以通信了
/*
@ Event.js
*/
import Vue from 'vue'
export default new Vue()
/*
@ Event.js用法
*/
import Event from 'Event.js'

//事件监听
Event.$on('hello', (str)=> {
     console.log(str)
})

//事件触发
var str = 'hello, word'
Event.$emit('hello', str)
上一篇 下一篇

猜你喜欢

热点阅读