简体   繁体   中英

Creating N tables (components) given N arrays in Vue.js

The way my code is right now, there are N arrays in my data. Each array contains the information of M students. The goal is to create N tables using (vue-draggable), and inside each, M draggable students, so that they can all be moved around, while updating each array. (n in 2 is just a filler, will use n in listNumber later on)

<template>
  <div class="row">
    
    <div class="col-3" v-for="n in 2"  :key="n">
      <h3>Draggable {{n}}</h3>
      <draggable class="list-group" :list="list1" group="people" @change="log">
        <div
          class="list-group-item"
          v-for="(element, index) in list1"
          :key="element.name"
        >
          {{ element.name }} {{ index }}
        </div>
      </draggable>
    </div>

  </div>

</template>

<script>
import draggable from "vuedraggable";
let id = 1;
export default {
  name: "two-lists",
  display: "Two Lists",
  order: 1,
  components: {
    draggable,
    list1:[],
  },
  data() {
    return {
      list1: [
        { name: "John", id: 1 },
        { name: "Joao", id: 2 },
        { name: "Jean", id: 3 },
        { name: "Gerard", id: 4 }
      ],
      list2: [
        { name: "Juan", id: 5 },
        { name: "Edgard", id: 6 },
        { name: "Johnson", id: 7 }
      ],
      listNumber:3,
    
    };
  },
  methods: {
    add: function() {
      this.list.push({ name: "Juan" });
    },
    replace: function() {
      this.list = [{ name: "Edgard" }];
    },
    clone: function(el) {
      return {
        name: el.name + " cloned"
      };
    },

  }
};
</script>

The way it is right now, my code returns 2 tables, Draggable 1, Draggable 2, however, each one's contents is only pulling from list1. Is there anyway that Draggable 1 has the items from list1, and Draggable 2 has the items from list2?

Probably the easiest approach is to refactor the data as an object, with the key name being the variable you want - ie:

people: {  
  1: [
        { name: "John", id: 1 },
        { name: "Joao", id: 2 },
        { name: "Jean", id: 3 },
        { name: "Gerard", id: 4 }
  ],
  2: [
        { name: "Juan", id: 5 },
        { name: "Edgard", id: 6 },
        { name: "Johnson", id: 7 }
  ],
}

Then in your template you can reference the object property:

<div class="col-3" v-for="n in 2"  :key="n">
      <h3>Draggable {{n}}</h3>
      <draggable class="list-group" :list="people[n]" group="people" @change="log">
      <div
          class="list-group-item"
          v-for="(element, index) in people[n]"
          :key="element.name"
        >
          {{ element.name }} {{ index }}
        </div>
      </draggable>
    </div>
  </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM