1.通过$children
不常用,因为通过数组下标才能拿到具体的子组件,有不确定性;
2.$refs
demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn ref="myCpn"></cpn>
<button @click="btnClick">按钮</button>
</div>
<template id="cpn">
<div>
<h2>我是子组件</h2>
</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el:"#app",
data:{
},
methods: {
btnClick(){
// this.$children[0].showMessage(); //不常用
// console.log(typeof this.$children);
this.$refs.myCpn.showMessage(); //常用
}
},
components:{
cpn:{
template:"#cpn",
methods:{
showMessage(){
console.log("showMessage");
}
}
}
}
});
</script>
</body>
</html>