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