【发布时间】:2021-06-10 07:39:51
【问题描述】:
嗯,我对 VueJS 有点陌生.. 现在我正在学习组件的工作方式。
当我尝试更新传递给在子组件中用作 v-model 的子组件的父数据参数时,我感到困惑。
我将添加一个示例,以便您理解我在说什么(我很难解释自己)
注意:我使用数组作为 v-model,因为我需要一种方法来遍历所有复选框 v-model 并稍后更新它们
我即将展示的示例是在旅途中编写的。所以它不是实际的代码,但你可以从中得到概念。
假设我们有以下模板:
<script type="x-template id="tree">
<table>
<thead>
<tr>
<th>Tree-Item</th>
<th>check chilld</th>
</tr>
</thead>
<tbody>
<template v-for="child in item.childrens">
<tr v-if="child.childrens.length <= 0">
<td>{{child.name}}</td>
<td>
<input type="checkbox" v-model="checkboxes[child.id].value" :value="1" />
</td>
</tr>
<tr v-else>
<td colspan="2">
<tree :item="child" :checkboxes="checkboxes"></tree>
</td>
</tr>
</template>
</tbody>
</table>
</script>
组件:
Vue.component("tree", {
template: "#tree",
props: {
item: Object,
checkboxes: []
}
}
vue 对象
var mainVue = new Vue({
el: "#app",
data: {
treeData: {
id: 0,
name: "a name",
childrens: [
{
id: 1,
name: "b name",
childrens: []
}, {
id: 2
name: "c name"
childrens: [
{
id: 3,
name: "d name",
childrens: []
},
{
id: 4,
name: "d name",
childrens: []
},
{
id: 5,
name: "d name",
childrens: []
}
]
}
]
},
checkboxes: []
}, mounted: function() {
//looping all the childrens... setting checkboxes array to contain data for each index of child
// checkboxes array now contains the objects of - [{value: 0},{value: 0},{value: 0},{value: 0},{value: 0},{value: 0}]
}
});
我的应用将如下所示:
<div id="app">
<tree :item="treeData" :checkboxes="checkboxes"></tree>
</div>
现在它可以工作了。如果我将mounted函数中的数组值之一更改为1,它将被设置为选中。但我的问题是我也想实时更新它。
所以如果我有一个按钮,让我们说:
<div id="app">
<tree :item="treeData" :checkboxes="checkboxes"></tree>
<button @click="changeCheckboxes">a button</button>
</div>
我将添加一个方法来将“复选框”数组更改为新的:
changeCheckboxes: function() {
this.checkboxes = [{value: 1}, {value: 0}, {value: 1}, {value: 0}, {value: 1}, {value: 0}];
}
它不会更新组件,我不会看到任何效果..即使我会使用 this.$forceUpdate()
所以在我向您简要介绍了详细信息之后。 是否有任何选项可以直接从根 vue 应用更新子组件中的 v-model?
感谢您的宝贵时间!希望我们能弄清楚:)
【问题讨论】:
-
看看reactivity docs on arraysVue 无法检测到你的更改
-
好的,注意了。尝试将复选框从 [] 更改为 {} 结果是一样的
标签: vue.js vue-component v-model