您的位置:首页 > Web前端 > Vue.js

vue --- > 获取子组件数据的一个应急方案$refs

2019-07-01 20:22 309 查看

使用$refs需要注意以下2点:
1.html方法使用子组件时,需使用ref = “xxx” 声明.
2.在父组件中使用,this.refs.xxx.msg 获取数据

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<div id="app">
<p>{{ message }}</p>
<my-component ref="comA"></my-component>
<button @click="handleRef">ref获取子组件数据</button>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>

Vue.component('my-component',{
template:'<button @click="sendMessage">派发事件</button>',
data:function(){
return {
msg:'来自子组件'
}
}

})
const app = new Vue({
el:'#app',
data:{
message: ''
},
methods:{
handleRef:function(){
this.message = this.$refs.comA.msg
}
}
})
</script>
</body>
</html>


参考《Vue.js实战》P82

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: