search

Home  >  Q&A  >  body text

"Using the v-for directive for array element and attribute destructuring"

When using an object array, is it possible to simultaneously assign the current object to a variable and deconstruct its properties in a v-for loop? like this:

<div v-for="(person = {name, age}, index) in persons">

Ultimately I would like to be able to use both the entire person object and its properties in the template.

P粉420958692P粉420958692390 days ago639

reply all(1)I'll reply

  • P粉115840076

    P粉1158400762023-11-06 15:56:06

    As far as I know, you can't do both at the same time.

    However, you can deconstruct it, for example:

    <div v-for="({name, age}, index) in persons">
    

    You can then access the correct element via the index: persons[index].


    Example:

    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>

    reply
    0
  • Cancelreply