记录一下vue组件间通信方式

父子组件通信

  • 创建子组件
<template>
    <div>
        <h2>子组件部分</h2>
        <p>{{msg}}</p>
    </div>
</template>

<script>
export default {
  name: 'Child',
  props: ['msg'],
  data () {
    return {
     
    }
  }
}
</script>

<style scoped>

</style>
  • 在App.vue中注册Child组件
<template>
  <div id="app">
     <child msg='hello'></child>
  </div>
</template>

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

    }
  },
  methods: {

  }
}
</script>

子父组件通信

  • 在子组件中创建一个按钮,给按钮绑定点击事件
  • 使用$emit来触发一个自定义事件,并传递一个参数
<template>
    <div>
        <h2>子组件部分</h2>
        <!-- 子组件向父组件传值或更新父组件值 -->
        <button v-on:click="goParent">向父组件传值</button>
    </div>
</template>

<script>
export default {
  name: 'Child',
  props: ['msg'],
  data () {
    return {
     
    }
  },
  methods:{
      goParent(){
        this.$emit('goto','来自于子组件的值')
      }
  }
}
</script>
  • 在父组件中监听该自定义事件并做处理
<template>
  <div id="app">
     <child msg='hello' v-on:goto='go'></child>
  </div>
</template>

<script>
import child from '../components/Child'
export default {
  name: 'Home',
  components:{
    child
  },
  data() {
    return {
    
    }
  },
  methods: {
    go(data){
      console.log(data);
    }
  }
}
</script>

兄弟组件通信

  • 创建中央事件总线
import Vue from 'Vue'

export default new Vue
  • 第一个组件
<template>
    <div>
        <h2>第一个组件</h2>
        <button v-on:click="sendMsg">向组件传值</button>
    </div>
</template>

<script>
import bus from '../assets/js/eventBus'
export default {
  name: 'firstChild',
  data () {
    return {
     
    }
  },
  methods:{
      sendMsg(){
        bus.$emit('one','来自于第一个组件的值')
      }
  }
}
</script>

<style scoped>

</style>
  • 第二个组件
<template>
    <div>
        <h2>第二个组件</h2>
        <p>接受过来的参数:{{msg}}</p>
    </div>
</template>

<script>
import bus from '../assets/js/eventBus'
export default {
  name: 'secondChild',
  data () {
    return {
      msg: 'mo'
    }
  },
  mounted() {
        var self = this
        bus.$on('one',function(msg){
            self.msg = msg
        })
  }
}
</script>

<style scoped>

</style>
  • 在父组件中,注册这两个组件
<template>
  <div id="app">
   <firstChild></firstChild>
   <secondChild></secondChild>
  </div>
</template>

<script>
import firstChild from '../components/firstChild'
import secondChild from '../components/secondChild'

export default {
  name: 'Main',
  components:{
    firstChild,
    secondChild
  }
}
</script>

<style>

</style>

sprite
10 声望0 粉丝

心向往之,行必能至!