在 Vue.js 中,this.$emit('update:modelValue', value)
通常用于触发 v-model
的更新。父组件可以通过 v-model
绑定一个变量来接收子组件传递的值。
假设你有一个子组件 ChildComponent
,它通过 this.$emit('update:modelValue', 1)
向父组件传递值。父组件的写法如下:
父组件
<template>
<div>
<!-- 使用 v-model 绑定子组件的 modelValue -->
<ChildComponent v-model="parentValue" />
<p>父组件接收到的值: {{ parentValue }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentValue: 0 // 初始值
};
}
};
</script>
子组件
<template>
<div>
<button @click="updateValue">更新值</button>
</div>
</template>
<script>
export default {
props: {
modelValue: {
type: Number,
default: 0
}
},
methods: {
updateValue() {
// 触发 update:modelValue 事件,传递新值
this.$emit('update:modelValue', 1);
}
}
};
</script>
解释
-
父组件:
- 使用
v-model
绑定parentValue
到子组件的modelValue
。 parentValue
是父组件中的一个数据属性,用于存储子组件传递的值。
- 使用
-
子组件:
- 通过
props
接收modelValue
。 - 在
updateValue
方法中,使用this.$emit('update:modelValue', 1)
向父组件传递新值。
- 通过
运行效果
- 当你在子组件中点击按钮时,
parentValue
的值会被更新为1
,并在父组件中显示。
这种方式是 Vue.js 中实现父子组件双向数据绑定的常见模式。
父级也可以
:path.sync=“path”
子级
prop:[path]
this.$emit('update:path', 1)