Как использовать Vue-draggable и Vuex для динамического разделения одного списка на несколько? - PullRequest
0 голосов
/ 08 июня 2019

У меня есть массив, который принимает от пользователя ответы от нескольких вопросов.Эти значения хранятся в моем магазине Vuex, а результаты отображаются на экране в перетаскиваемом списке.

computed: {
  allValues() {
        const val1 = this.responses1
        const val2 = this.responses2
        const val3 = this.responses3
        const val4 = this.responses4
        const val5 = this.responses5
        const val6 = this.responses6
        const val7 = this.responses7
        const coreValues = val1.concat(val2,val3,val4,val5,val6,val7)
        this.$store.dispatch('corevalues/loadCoreValues', coreValues)
        return this.$store.getters['corevalues/getCoreValues']
    }
  }

Перетаскиваемый список

 <draggable :v-model="allValues" 
    options:='group: "allValues"'>
     <transition-group>
      <div v-for="val in allValues" :key="val.value">
          {{val.value}}
      </div>
    </transition-group>
 </draggable>

{{ allValues }}

Однако на экранехотя я могу перетаскивать и сортировать значения - они не переупорядочиваются в Vuex Store, только на экране.

1) Мне нужно, чтобы они переупорядочили в магазине.

2) Несмотря на то, что с помощью ввода пользователя создается один массив, я требую от пользователейиметь возможность перетаскивать значения во второй или даже третий столбец, чтобы сгруппировать их.

Как мне сделать так, чтобы мои изменения на экране отражались в хранилище - даже в новом массиве -и чтобы мой список можно было разбить на несколько столбцов?

Это моя песочница моего кода: https://codesandbox.io/embed/vue-template-j53g3

РЕДАКТИРОВАТЬ : после ответа Саби

Я реализовал следующий код:

watch:{
    allValues: {
        handler: function(newValue) {
          console.log('here', newValue)
          this.$store.dispatch("corevalues/loadCoreValues", newValue);
        }
    },
    deep: true // deep watching changes
  },

Но, как показано на рисунке ниже, шаблон {{ allValues }} остается в том же порядке, даже если он был переупорядочен на экране.

enter image description here

2-е редактирование

Обновлен код в соответствии с рекомендациями.

Консоль регистрирует сообщение «Drag Ended», нокак показано на скриншоте ниже, основные значения в магазине не обновлялись - это после «перезагрузки состояния» с помощью инструментов разработчика.

enter image description here

1 Ответ

1 голос
/ 08 июня 2019

Вы можете использовать

watch:{
 list: {
        handler: function(newValue) {
            // do your job 

           // this.$store.commit("updateList", value);
           // commit your changes to store 
  }

        },
        deep: true // deep watching changes
    }

}

для проверки изменений и повторных заказов, также хорошим решением является создание кнопки для сохранения пользовательских изменений в хранилище.

ОБНОВЛЕНИЕ Таким образом, изменения перетаскивания не отслеживаются :( ... Но в vue-dragggable есть события @end enter image description here В конце перетаскивания вы можете сохранить отсортированный массив в хранилище vuex

 <draggable :v-model="allValues" @end="onEnd">
          <transition-group>
            <div v-for="val in allValues" :key="val.value">{{val.value}}</div>
          </transition-group>
        </draggable>

И в методах

  methods: {
    onEnd(){
      console.log("Drag ended")
        this.$store.dispatch("corevalues/loadCoreValues", this.allValues);
    },

Наконец-то

<script>
import draggable from "vuedraggable";
export default {
  components: {
    draggable
  },
  data() {
    return {
      num: 1,
      allValues:[],
      responses1: [],
      responses2: [],
      responses3: [],
      responses4: [],
      responses5: [],
      responses6: [],
      responses7: [],
      question: [
        {
          id: 1,
          question: "What do you believe defines the culture at your company?"
        },
        {
          id: 2,
          question:
            "What values do you bring to your work that you consistently uphold whether or not they are rewarded?"
        },
        {
          id: 3,
          question:
            "What do you truly stand for in your work? What do you believe your company truly stands for?"
        },
        {
          id: 4,
          question:
            "What do your customers believe about you? What do they believe you stand for?"
        },
        {
          id: 5,
          question:
            "What values does your company consistently adhere to in the face of obstacles?"
        },
        {
          id: 6,
          question: "What are your company’s greatest strengths?"
        },
        {
          id: 7,
          question:
            "What are the top three to five most important behaviours you should expect from every employee (including you)?"
        }
      ]
    };
  },
  computed: {
    number(number) {
      return this.number + number;
    },
    // allValues: {
    //   // get() {
    //   //   const val1 = this.responses1;
    //   //   const val2 = this.responses2;
    //   //   const val3 = this.responses3;
    //   //   const val4 = this.responses4;
    //   //   const val5 = this.responses5;
    //   //   const val6 = this.responses6;
    //   //   const val7 = this.responses7;
    //   //   const coreValues = val1.concat(val2, val3, val4, val5, val6, val7);
    //   //   // this.$store.dispatch("corevalues/loadCoreValues", coreValues);
    //   //   // return this.$store.getters["corevalues/getCoreValues"];
    //   //   return coreValues;
    //   // },
    // }
  },
  watch: {
    responses1: {
      handler: function(newValue) {
        console.log(newValue)
        this.appendWithoutDublicates(this.responses1)
      },
      deep: true // deep watching changes if you need
    },
    // responses from 2 to 7: { 
    //   handler: function(newValue) {
    //     console.log(newValue)
    //     this.appendWithoutDublicates(this.responses1)
    //   },
    //   deep: true // deep watching changes if you need
    // },
    allValues: {
      handler: function(newValue) {
        console.log(newValue)
       this.$store.dispatch("corevalues/loadCoreValues", newValue);
      },
      deep: true // deep watching changes if you need
    },

  },
  methods: {
    appendWithoutDublicates(values){
      this.allValues = this.allValues.concat(values.filter(item => {
            return this.allValues.findIndex(obj => obj.value === item.value) < 0;
         }));
    },
    onEnd() {
      console.log("Drag ended");
      console.log(this.allValues);
      this.$store.dispatch("corevalues/loadCoreValues", this.allValues);
    },
    setValues() {
      // this.allValues = coreValues
    },
    questionNumber(num) {
      this.num += num;
    },
    addresponse1: function() {
      var elem = document.createElement("tr");
      this.responses1.push({
        value: ""
      });
    },
    removeElement1: function(index) {
      this.responses1.splice(index, 1);
    },
    addresponse2: function() {
      var elem = document.createElement("tr");
      this.responses2.push({
        value: ""
      });
    },
    removeElement2: function(index) {
      this.responses2.splice(index, 1);
    },
    addresponse3: function() {
      var elem = document.createElement("tr");
      this.responses3.push({
        value: ""
      });
    },
    removeElement3: function(index) {
      this.responses3.splice(index, 1);
    },
    addresponse4: function() {
      var elem = document.createElement("tr");
      this.responses4.push({
        value: ""
      });
    },
    removeElement4: function(index) {
      this.responses4.splice(index, 1);
    },
    addresponse5: function() {
      var elem = document.createElement("tr");
      this.responses5.push({
        value: ""
      });
    },
    removeElement5: function(index) {
      this.responses5.splice(index, 1);
    },
    addresponse6: function() {
      var elem = document.createElement("tr");
      this.responses6.push({
        value: ""
      });
    },
    removeElement6: function(index) {
      this.responses6.splice(index, 1);
    },
    addresponse7: function() {
      var elem = document.createElement("tr");
      this.responses7.push({
        value: ""
      });
    },
    removeElement7: function(index) {
      this.responses7.splice(index, 1);
    }
  }
};
</script>

И обновление можно перетаскивать также

<draggable :list="allValues" @end="onEnd">
  <transition-group>
    <div v-for="val in allValues" :key="val.value">{{val.value}}</div>
  </transition-group>
</draggable>
...