vue-cli 工程中 父组件通过ref 获取子组件的值
参考文档子组件引用尽管有 prop 和事件,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个引用 ID。例如:<div id="parent"><user-profile ref="profile"></user-profile&g
·
参考文档
子组件引用
尽管有 prop 和事件,但是有时仍然需要在 JavaScript 中直接访问子组件。
为此可以使用 ref 为子组件指定一个引用 ID。例如:
<div id="parent">
<user-profile ref="profile"></user-profile>
</div>
var parent = new Vue({ el: '#parent' })
// 访问子组件实例
var child = parent.$refs.profile
当 ref 和 v-for 一起使用时,获取到的引用会是一个数组,包含和循环数据源对
应的子组件。
$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅是一个直接
操作子组件的
应急方案——应当避免在模板或计算属性中使用 $refs。
具体使用方法:
在父组件中 我现在在 app.vue中
<template>
<div id="app">
{{ a }}
<button @click="getchild">通过ref得到子组件的值</button>
<!-- 使用组件 -->
<three ref="mesage"/>
</div>
</template>
<script>
import three from './components/three'
export default {
components:{
three,
},
data(){
return {
a:'我是父组件',
}
},
methods:{
getchild(){
// 通过this.$refs调用
console.log(this.$refs.mesage.mes)
}
}
}
</script>
子组件three.vue
<template>
<div class="three">
{{mes}}
</div>
</template>
<script>
export default {
data() {
return {
mes:'666'
};
}
};
</script>
更多推荐
已为社区贡献20条内容
所有评论(0)