1.使用$children的方法
<body>
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
<button @click="btnClick">按钮</button>
</div>
<template id="cpn">
<div>我是子组件</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
message: "你好啊"
},
methods:{
btnClick(){
console.log(this.$children);
for(let c of this.$children){
console.log(c.name);
c.showMessage();
}
}
},
components: {
cpn: {
template: '#cpn',
data(){
return {
name:"我是子组件的name"
}
},
methods: {
showMessage() {
console.log('showMessage');
}
}
}
}
})
</script>
</body>
2.使用$refs的方法(这种更常用)
<body>
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn ref="aaa"></cpn>
<button @click="btnClick">按钮</button>
</div>
<template id="cpn">
<div>我是子组件</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
message: "你好啊"
},
methods: {
btnClick() {
// 2.$refs(这种用法比较多-> 对象类型,默认是一个空的对象,ref='')
console.log(this.$refs.aaa.name);
}
},
components: {
cpn: {
template: '#cpn',
data() {
return {
name: "我是子组件的name"
}
},
methods: {
showMessage() {
console.log('showMessage');
}
}
}
}
})
</script>
</body>