组件之间通信(子传父$emit)

通过$emit 实现子组件向父组件通信

vm.$emit( event, arg )
//$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
//父组件
<template>
 <div>
  <h1>{{title}}</h1>
  <child @getMessage="showMsg"></child>
 </div>
</template>
  
<script>
 import Child from '../components/child.vue'
 export default {
  components: {Child},
  data(){
   return{
    title:''
   }
  },
  methods:{
   showMsg(title){
    this.title=title;
   }
 }
 }
</script>
//子组件
<template>
 <h3>我是子组件!</h3>
</template>
<script>
 export default {
  mounted: function () {
   this.$emit('getMessage', '我是父组件!')
  }
 }
</script>

 通过$parent,$childern父子组件通信(也可以用来作为父子传子通信)

使用 this.$parent查找当前组件的父组件。
使用 this.$children查找当前组件的直接子组件,可以遍历全部子组件, 需要注意 $children 并不保证顺序,也不是响应式的。
使用 this.$root查找根组件,并可以配合$children遍历全部组件。
使用 this.$refs查找命名子组件。

<!-- 父组件-->
<template>
<div class="game">
    <h2>{{ msg }}</h2>
    <LOL ref="lol"></LOL>
    <DNF ref="dnf"></DNF>
</div>
</template>
<script>
import LOL from '@/components/game/LOL'
import DNF from '@/components/game/DNF'
export default {
    name: 'game',
    components: {
        LOL,
        DNF
    },
    data () {
        return {
            msg: 'Game',
            lolMsg:'Game->LOL',
            dnfMsg:'Game->DNF',
        }
    },
    methods: {
    
    },
    mounted(){ //注意 mounted
        
        //读取子组件数据,注意$children子组件的排序是不安全的
        console.log(this.$children[0].gameMsg);//LOL->Game
        
        //读取命名子组件数据
        console.log(this.$refs.dnf.gameMsg);//DNF->Game
        
        //从根组件查找组件数据
        console.log(this.$root.$children[0].msg); //APP
        console.log(this.$root.$children[0].$children[0].msg); //Game
        console.log(this.$root.$children[0].$children[0].$children[0].msg); //Game->LOL
        console.log(this.$root.$children[0].$children[0].$children[1].msg); //Game->DNF
    }
}
</script>
<style lang="css">
.game{
    border: 1px solid #00FF00;
    width: 200px;
}  
</style>
<!--子组件LOL -->
<template>
  <div class="lol">
    <h2>{{ msg }}</h2>
  </div>
</template>

<script>
export default {
    name: 'LOL',
    data () {
        return {
            msg: 'LOL',
            gameMsg:'LOL->Game',
        }
    },
    methods:{

    },
    created(){
        //读取父组件数据
        this.msg = this.$parent.lolMsg;
    }
}
</script>
<!--子组件DNF -->
<template>
  <div class="dnf">
    <h2>{{ msg }}</h2>
  </div>
</template>

<script>
import Bus from '../../utils/bus.js'
export default {
    name: 'DNF',
    data () {
        return {
            msg: 'DNF',
            gameMsg:'DNF->Game',
        }
    },
    methods:{

    },
    created(){
        //从根组件向下查找父组件数据
        this.msg = this.$root.$children[0].$children[0].dnfMsg;
    }
}
</script>

 

 

 

posted @ 2019-11-12 10:12  半雨烟缘  阅读(301)  评论(0编辑  收藏  举报