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

 

转载于:https://www.cnblogs.com/phptree/p/10082684.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值