[Vuejs]-V-if and v-else not working after data array change

0👍

if you are using something like

r.meta.fields = newValue

then this won’t work.

you should use

Vue.set(r.meta.fields, indexOfItem, newValue)

document here: vue update array

0👍

You could create a mapping for the sort icons and handle the changes on click:

const vm = new Vue({
  el: '#app',

  data() {
    const iconMap = {
      sort: {
        'asc': 'fa-sort-up',
        'desc': 'fa-sort-down'
      }
    };

    return {
      r: {
        meta: {
          fields: [
            {
              label: 'field #1',
              sortable: false,
              sort_direction: 'asc',
              icon: ''
            }, 
            {
              label: 'field #2',
              sortable: true,
              sort_direction: 'desc',
              icon: iconMap.sort['desc']// Initially sortable in descending order
            }
          ]
        }
      },

      iconMap
    }
  },

  methods: {
    sortField(field) {
      let direction = (field.sort_direction === 'asc') ? 'desc' : 'asc';
      let icon = this.iconMap.sort[direction] || '';

      field.sort_direction = direction;
      field.icon = icon;
    }
  }
})

Template or HTML

<div id="app">
  <table>
   <tr>
    <th v-for="field in r.meta.fields" :key="field.label">
       {{field.label}}

       <a href="#"
        :class="field.icon"
        @click.prevent="sortField(field)"></a>
    </th>
   </tr>
  </table>
</div>

Leave a comment