有时候需要父组件直接访问子组件,子组件直接访问父组件,或者是子组件访问根组件:
- 1.父组件访问子组件:使用 $children 或者 $refs (reference:引用);
- 2.子组件访问父组件:使用 $parent
使用 $children 访问子组件
1.this.$children是一个数组类型,它包括所有子组件对象;
2.我们这里通过一个遍历,取出所有子组件的message状态;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--
有时候需要父组件直接访问子组件,子组件直接访问父组件,或者是子组件访问根组件,
1.父组件访问子组件:使用$children或者$refs reference(引用)
2.子组件访问父组件:使用$parent
先看下$children的访问
1.this.$children是一个数组类型,它包括所有子组件对象;
2.我们这里通过一个遍历,取出所有子组件的message状态;
-->
<div id="app">
<childrencpn></childrencpn>
<childrencpn></childrencpn>
<childrencpn></childrencpn>
<button @click="btnClick">按钮</button>
</div>
<template id="childrencpn">
<div>我是一个子组件</div>
</template>
<script src="../js/vue.js"></script>
<script>
const vue = new Vue({
el: '#app',
data: {
message: '你好啊'
},
methods: {
btnClick() {
/*
* this.$children
* 在控制台打印出来其实是一个数组类型:VueComponent
* 子组件也可以向另一个组件访问
* */
console.log(this.$children)
this.$children[0].showMessage();
for (const argument of this.$children) {
argument.showMessage();
console.log(argument.name);
}
}
},
components: {
childrencpn: {
template: '#childrencpn',
data() {
return{
name:'12345678'
}
},
methods: {
showMessage() {
console.log("父组件调用子组件");
}
}
}
}
});
</script>
</body>
</html>
其实用这种方法去获取子对象的对象属性,为以后的增加子组件时,留下了隐患,因为组件顺序可能会改变,到那时就会产生bug
$refs 解决 $children的问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<childrencpn ref="aaa"></childrencpn>
<childrencpn ref="bbb"></childrencpn>
<childrencpn ref="cc"></childrencpn>
<button @click="btnClick">按钮</button>
</div>
<template id="childrencpn">
<div>我是一个子组件</div>
</template>
<script src="../js/vue.js"></script>
<script>
const vue = new Vue({
el: '#app',
data: {
message: '你好啊'
},
methods: {
btnClick() {
console.log(this.$refs);
console.log(this.$refs.aaa.name);
}
},
components: {
childrencpn: {
template: '#childrencpn',
data() {
return {
name: '12345678'
}
},
methods: {
showMessage() {
console.log("父组件调用子组件");
}
}
}
}
});
</script>
</body>
</html>