vue.jsvuetify.jspinia

proper way to compute a value based on a store?


I have a view that stores items in a reservation liste. The reservation list sits in a store.

this is a vuetify switch

<v-switch
  hide-details
  inset
  color="black"
  :value="isReserved"
  @change="toggleReservation"
  :disabled="isReserveDisabled"></v-switch>
v-card-actions>

this is the computed:

isReserved() {
  return equipmentStore.reservations.some(
    item => item.id === this.id
  );
},

clicking the switch will add and remove id's to the equipmentStore.reservations array. This works but the state of the button is not reflecting that. It stays in to off position.

If we change it to

<v-switch
  hide-details
  inset
  color="black"
  v-model="isReserved"
  @change="toggleReservation"
  :disabled="isReserveDisabled"></v-switch>

it does work but there is the obivous warning in the console that the computed is readonly.

What would be the proper way to reflect the state of this button based on a value in the store?


Solution

  • This Warning occurred due to you use computed property.which means it cannot be modified directly.

    we can use another way Getter(get()) and Setter(set()) methods as below.

    just update computed hook as below snippet code:

    computed: {
      isReserved: {
        get() {
          return equipmentStore.reservations.some(item => item.id === this.id);
        },
        set(value) {
          if (value) {
            // Add the item to reservations if not already present
            if (!this.isReserved) {
              equipmentStore.reservations.push({ id: this.id });
            }
          } else {
            // Remove the item from reservations
            equipmentStore.reservations = equipmentStore.reservations.filter(
              item => item.id !== this.id
            );
          }
        }
      }
    }
    

    and also update a v-switch code in template tag as below:

    <v-switch
      hide-details
      inset
      color="black"
      v-model="isReserved"
      :disabled="isReserveDisabled"></v-switch>
    

    It's directly update your store. so we don't need to update v-modal value.

    I hope it's working for you.