一、父子组件的访问方式
1.父组件访问子组件:使用’$ children’ 或者’$ refs’
父组件模板:
<div id="app">
<cpn></cpn>
<cpn></cpn>
<my-cpn></my-cpn>
<y-cpn></y-cpn>
<cpn ref="aaa"></cpn>
<button @click="btnClick">按钮</button>
</div>
子组件模板:
<template id="cpn">
<div>我是子组件</div>
</template>
父子组件:
<script>
const app = new Vue({
el: '#app',
data: {
},
methods: {
btnClick() {
// 1.$children
// console.log(this.$children);
// for (let c of this.$children) {
// console.log(c.name);
// c.showMessage();
// }
// console.log(this.$children[3].name);
// 2.$refs => 对象类型, 默认是一个空的对象
console.log(this.$refs.aaa.name);
}
},
//子组件
components: {
cpn: {
template: '#cpn',
data() {
return {
name: '我是子组件的name'
}
},
methods: {
showMessage() {
console.log('showMessage');
}
}
},
}
})
</script>
用$ refs可以直接确定选择的组件标签,例如:时,methods选中为:this.$ refs.aaa.name。
2.子组件访问父组件:使用$parent(开发时不建议使用)
$ parent:只能访问上一层父组件。
$ root:能访问根组件。