Hi似乎不是迭代和编辑对象(不是数组)的最佳实践。但是,有没有一种最好的方法可以尽可能简单地处理对象数组呢?
https://jsfiddle.net/woto/q9zqefq0/11/
new Vue({
el: '#app',
data: {
object1: {
'first': 'second'
},
object2: [
{'key': 'first', 'value': 'second' }
]
}})
--
<script src="https://unpkg.com/vue"></script>
<div id="app">
<!-- Is there a way to make it work? -->
<!-- `k` value of object is not reactive(?) -->
<div v-for="(v, k) in object1">
<p> {{ k }} | {{ v }} </p>
<input type="text" class="form-control" v-model="k">
<input type="text" class="form-control" v-model="object1[k]">
</div>
<br />
<!-- This works fine like a charm -->
<div v-for="item in object2">
<p> {{ item }} </p>
<input type="text" class="form-control" v-model="item.key">
<input type="text" class="form-control" v-model="item.value">
</div>
</div>
最佳答案
这是一件非常愚蠢的事情,但是如果您真的想将对象的属性名绑定到输入,您可以这样做:
new Vue({
el: '#app',
data: {
object1: {
'first': 'second'
},
object2: [
{'key': 'first', 'value': 'second' }
]
},
methods: {
updateObject(e, old, prop) {
let val = this[prop][old];
this.$delete(this[prop], old);
this.$set(this[prop], e.srcElement.value, val);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<div v-for="(v, k) in object1">
<p> {{ k }} | {{ v }} </p>
<input type="text" class="form-control" :value="k" @input="updateObject($event, k, 'object1')">
<input type="text" class="form-control" v-model="object1[k]">
</div>
<br />
<div v-for="item in object2">
<p> {{ item }} </p>
<input type="text" class="form-control" v-model="item.key">
<input type="text" class="form-control" v-model="item.value">
</div>
</div>
关于javascript - 如何像数组集合一样编辑对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49538525/