Vue父子组件访问方式
1.父组件访问子组件
使用$children或$refs,但在Vue3中$children属性已被移除
$refs与ref一起使用,通过ref给组件绑定一个ID,通过this.$ref.ID就可以访问到该组件了
具体代码实现
<body>
<div id='app'>
<cpna></cpna>
<cpna></cpna>
<cpna ref="ref"></cpna>
<button @click="btnClick">按钮</button>
</div>
<template id="cpn">
<div>我是子组件</div>
</template>
<script src='../js/vue.js'></script>
<script>
const app = new Vue ({
el: '#app',
data: {
message:'hello'
},
methods:{
// 1.$children Vue3中已弃用,使用方法如下
btnClick() {
// console.log(this.$children);
// for(let a of this.$children){
// console.log(a.name);
// a.showMessage();
// }
// 2.$refs(对象类型,默认是一个空的对象)
// 取子组件内容
console.log(this.$refs.ref.name);
// 打印的是子组件
this.$refs.ref.showMessage();
}
},
components: {
cpna: {
template:'#cpn',
data() {
return {
name:'我是子组件的name'
}
},
methods:{
showMessage() {
console.log('showMessage');
}
}
}
}
})
</script>
</body>
2.子组件访问父组件
通过$parent可实现访问
具体实现:
<body>
<div id='app'>
<cpna></cpna>
</div>
<template id="cpn">
<div>
<p>我是子组件</p>
<button @click="btnClick">按钮</button>
</div>
</template>
<script src='../js/vue.js'></script>
<script>
const app = new Vue ({
el: '#app',
data: {
message:'我是父组件'
},
components: {
cpna:{
template:'#cpn',
methods: {
btnClick() {
// 第一个打印的Vue是因为父组件就是vue实例
console.log(this.$parent.message);
// 打印根组件data里的message,这里的父组件也是根组件
console.log(this.$root.message);
}
}
}
}
})
</script>
</body>
注意事项:
- 尽管在Vue开发中,我们允许通过$parent来访问父组件,但是在真实开发中尽量不要这样做。
- 子组件应该尽量避免直接访问父组件的数据,因为这样耦合度太高。
如果我们将子组件放在另外一个组件之内,很可能该父组件没有对应的属性,往往会引起问题。 - 另外,通过$parent直接修改父组件的状态,那么父组件中的状态将变得飘忽不定,很不利于我的调试和维护