初識vue 2.0(10):使用$parent、$children父子組件通訊

使用 this.$parent查找當前組件的父組件。
使用 this.$children查找當前組件的直接子組件,能夠遍歷所有子組件, 須要注意 $children 並不保證順序,也不是響應式的。
使用 this.$root查找根組件,並能夠配合$children遍歷所有組件。
使用 this.$refs查找命名子組件。css

 

例子:vue

父組件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.vuethis

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

<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>
相關文章
相關標籤/搜索