在vue2 中父组件通过ref传值子组件接受
时间: 2025-02-07 15:04:53 浏览: 37
在 Vue.js 2.x 中,父组件想要向子组件传递值通常会使用 `ref` 和 props 来实现。首先,在父组件中,你可以创建一个 ref 对象来存储你要传递的数据:
```html
<template>
<div>
<child-component :value="parentValue" ref="childRef"></child-component>
<button @click="updateChildValue">更新子组件值</button>
</div>
</template>
<script>
export default {
data() {
return {
parentValue: '初始值',
};
},
methods: {
updateChildValue() {
this.parentValue = '新值';
},
},
components: {
ChildComponent,
},
};
</script>
```
然后,在子组件的模板上,你可以接收 `value` prop 并显示它:
```html
<template>
<div>{{ value }}</div>
</template>
<script>
export default {
props: ['value'],
};
</script>
```
当父组件的 `parentValue` 发生变化时,由于 `updateChildValue` 调用了 `this.parentValue` 的赋值操作,Vue 检测到变化并自动将新的值传递给子组件。
阅读全文
相关推荐

















