vue.js - v-for : Array element and destructuring of properties

标签 vue.js vuejs2 vue-component

处理对象数组时,是否可以在 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/

相关文章:

javascript - BootstrapVue 访问 slot 模板中的 b-table 行数据

javascript - Vue - v-如果列表中没有具有该名称的项目,则显示图像

javascript - 如何在 Firestore Web 上创建子文件夹和文档?

javascript - 更改组件的 html 元素类型

javascript - vue.js:定期重复后台查询的位置

javascript - Vue-Router 返回 "Cannot redefine property: $router"错误

javascript - 是否可以在生命周期内(beforeCreate)导入 vue 组件文件?

typescript - 在混合 ES/TS 项目中使用 Vue 组件

php - Laravel API 对后续请求的验证/保护 : no login/logout and no "users" table

javascript - 使用 vue 和 vue-router 确保 View 顺序的最佳实践