Search code examples
javascriptvuejs2vuetify.jsrubaxa-sortable

vuejs sortable change color on drag?


i am trying to implement Vue drag and drop using sortable and so far it seems to be working but how can i change the color of an element when the dragging starts?

The button outside the table element is the one whose color should change.

Here is a working codepen : https://codepen.io/anon/pen/pXRWeP

  <v-container>
      <v-data-table :headers="headers" :items="desserts" hide-actions 
   class="elevation-2">
        <template slot="items" slot-scope="props">
       <td >
        <v-btn class="handle" style="max-width: 28px;">
        <v-icon>drag_handle</v-icon>
        </v-btn></td>
      <td>{{ props.item.name }}</td>
      <td class="text-xs-right">{{ props.item.calories }}</td>
      <td class="text-xs-right">{{ props.item.fat }}</td>
      <td class="text-xs-right">{{ props.item.carbs }}</td>
      <td class="text-xs-right">{{ props.item.protein }}</td>
      <td class="text-xs-right">{{ props.item.iron }}</td>
    </template>
      </v-data-table>
    <v-btn>Change color of this button when dragging starts</v-btn>
  </v-container>


     new Vue({
   el: '#app',
  data: () => ({
    headers: [
    {
      text: "",
      align: "left",
      sortable: false
    },
    {
      text: "Dessert (100g serving)",
      align: "left",
      sortable: false,
      value: "name"
    },
    { text: "Calories", value: "calories" },
    { text: "Fat (g)", value: "fat" },
    { text: "Carbs (g)", value: "carbs" },
    { text: "Protein (g)", value: "protein" },
    { text: "Iron (%)", value: "iron" }
  ],
  desserts: [
    {
      value: false,
      name: "Lollipop",
      calories: 159,
      fat: 6.0,
      carbs: 24,
      protein: 4.0,
      iron: "1%"
    },
    {
      value: false,
      name: "Marshamallow",
      calories: 262,
      fat: 16.0,
      carbs: 23,
      protein: 6.0,
      iron: "7%"
    },
    {
      value: false,
      name: "Noughat",
      calories: 305,
      fat: 3.7,
      carbs: 67,
      protein: 4.3,
      iron: "8%"
    },
    {
      value: false,
      name: "Oreo",
      calories: 356,
      fat: 16.0,
      carbs: 49,
      protein: 3.9,
      iron: "16%"
    },
  ]
 }),
  mounted() {
   let table = document.querySelector(".v-datatable tbody");
   const _self = this;
   Sortable.create(table, {
     handle: ".handle",
      onEnd({ newIndex, oldIndex }) {
      const rowSelected = _self.desserts.splice(oldIndex, 1)[0]; 
      _self.desserts.splice(newIndex, 0, rowSelected); 
     }
   });
  }
 })

Thank you in advance guys.


Solution

  • You already have a function defined for onEnd in your Sortable.create call. Add one for onStart. Add a color key in data, and bind your button's color to it. In your onStart call, set _self.color equal to your new color; in onEnd, set it back to the old color.

    I modified your codepen with the result: https://codepen.io/djsmedes/pen/WqRdxm