在Vue中,当子组件较多时,通过this.$children
来一一遍历我们需要的一个组件是比较困难的,尤其是组件动态渲染时,他们的序列是不固定的。Vue提供了子组件索引的方法,用特殊的属性ref
为子组件指定一个索引的名字。
<html>
<head>
<title>Vue学习</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<component-a ref="compA"></component-a>
<button @click="handleMessage">获取组件A的内容</button>
{{message}}
</div>
<script type="text/javascript">
Vue.component("component-a", {
data: function () {
return {
message: '这是组件A的message'
}
},
template:'<div></div>'
})
var app = new Vue({
el: '#app',
data: {
message: ''
},
methods: {
handleMessage: function () {
this.message = this.$refs.compA.message
}
}
})
</script>
</body>
</html>
看密码