this.$children
<body>
<div id="app">
<cpn></cpn>
<button @click="btnClick">click</button>
</div>
<template id = 'cpn'>
<div>我是子元件</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'hello world'
},
methods: {
btnClick() {
console.log(this.$children);
this.$children[0].showMessage();
}
},
components: {
cpn: {
template: '#cpn',
methods: {
showMessage() {
console.log("showMessage");
}
}
}
}
})
</script>
</body>
this.refs
<body>
<div id="app">
<cpn ref="a"></cpn>
<cpn ref="b"></cpn>
<button @click="btnClick">click</button>
</div>
<template id = 'cpn'>
<div>我是子元件</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'hello world'
},
methods: {
btnClick() {
// $refs => 對象類型,預設是空對象
console.log(this.$refs.a.tmessage);
}
},
components: {
cpn: {
template: '#cpn',
data() {
return {
tmessage: 'test'
}
},
methods: {
showMessage() {
console.log("showMessage");
}
}
}
}
})
</script>
</body>