Vue之componet之$children
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../js/vue.js"></script>
<title>componet-children</title>
</head>
<body>
<div id="app">
<child></child>
<child></child>
<child></child>
<button @click="showchild">click me</button>
</div>
<!--child template-->
<template id="child">
<div>
<h1>I am child</h1>
<h1>{{childmessge}}</h1>
</div>
</template>
<script>
//childe componet
let child = Vue.component('child', {
template: "#child",
data() {
return {
childmessge: "I am from child",
name: "xiao li"
}
},
methods: {
show() {
alert("I come")
}
}
})
//root
new Vue({
el: "#app",
methods: {
showchild() {
console.log(this.$children);//查看$children
console.log(this.$children[1].name)//访问子组件数据项
this.$children[0].show();//访问子组件方法
}
},
components: {
child
}
})
</script>
</body>
</html>
运行效果:
点击按钮后:
总结:
访问当前实例的直接子组件。需要注意 $children 并不保证顺序,也不是响应式的。如果你发现自己正在尝试使用 $children 来进行数据绑定,考虑使用一个数组配合 v-for 来生成子组件,并且使用 Array 作为真正的来源。