【发布时间】:2025-12-30 08:30:10
【问题描述】:
我正在尝试结合使用 v-for 和 v-model 来为某些输入表单获取双向数据绑定。我想动态创建子组件。目前,我没有看到子组件更新父数据对象。
我的模板是这样的
<div class="container" id="app">
<div class="row">
Parent Val
{{ ranges }}
</div>
<div class="row">
<button
v-on:click="addRange"
type="button"
class="btn btn-outline-secondary">Add time-range
</button>
</div>
<time-range
v-for="range in ranges"
:box-index="$index"
v-bind:data.sync="range">
</time-range>
</div>
<template id="time-range">
<div class="row">
<input v-model="data" type="text">
</div>
</template>
还有这个js
Vue.component('time-range', {
template: '#time-range',
props: ['data'],
data: {}
})
new Vue({
el: '#app',
data: {
ranges: [],
},
methods: {
addRange: function () {
this.ranges.push('')
},
}
})
我也做了一个 js fiddle https://jsfiddle.net/8mdso9fj/96/
【问题讨论】:
-
您可以发出自定义事件以在 vue2 中将数据从子级发送到父级。你试过吗?
-
特别是,您正在尝试使用
.sync修饰符。您应该阅读how that works 的文档。 -
大家好。我确实尝试了 .sync 修饰符,但没有任何运气jsfiddle.net/8mdso9fj/97
-
v-model在道具上不起作用。您需要将其设置为发出update:data事件。
标签: javascript vue.js components vuejs2 vue-component