处理对象数组时,是否可以在 v-for
中使用-loop 将当前对象分配给变量并同时销毁其属性?像这样的东西:
<div v-for="(person = {name, age}, index) in persons">
最终,我正在寻找一种使用方法,例如两者全person
模板中的对象及其属性。
最佳答案
据我所知,你不能两者兼而有之。
但是,您可以解构,即
<div v-for="({name, age}, index) in persons">
然后您可以使用索引访问正确的元素:persons[index]
.例子:
new Vue({
el: "#app",
data: {
todos: [{
text: "Learn JavaScript",
done: false
},
{
text: "Learn Vue",
done: false
},
{
text: "Play around in JSFiddle",
done: true
},
{
text: "Build something awesome",
done: true
}
]
},
methods: {
toggle: function(index) {
this.todos[index].done = !this.todos[index].done
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="({text, done}, i) in todos">
<label>
<input type="checkbox"
v-on:change="toggle(i)"
v-bind:checked="done">
<del v-if="done">
{{ text }}
</del>
<span v-else>
{{ text }}
</span>
{{todos[i]}}
</label>
</li>
</ol>
</div>
关于vue.js - v-for : Array element and destructuring of properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65110748/