初识vue 2.0(10):使用$parent、$children父子组件通信

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

例子:

父组件Game.vue

<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.vue

<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.vue

<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>

猜你喜欢

转载自www.cnblogs.com/phptree/p/10082684.html