tnk479
tnk479

Reputation: 794

How to filter some vuex data in response to a select change

I'm new to VueJS and still trying to understand all of the constructs. I have a Vuex store and that has several arrays in the state. In a view that uses the vuex store through a computed property, I need to filter the data from the store when a select changes. I don't understand how to wire the select to the officeProjections data in the store.

 <select id="busyness"
                name="busyness"
                class="form-control mt-1"
                v-model="workloadLevels"
                @@change="onWorkloadFilterChange($event)">
            <option v-for="wl in workloadLevels" v-bind:value="wl.id">{{ wl.description }}</option>
        </select>

        <div v-for="op in officeProjections" class="mt-1">
            <div class="card">
                <div class="card-body">
                    <h3 class="card-title">{{ op.consultantName }}</h3>
                    <p>{{ op.workloadLevel }} <button type="button" v-bind:id="op.ConsultantId" class="btn btn-lg btn-info" data-toggle="popover" data-placement="right" v-bind:data-content="op.comment"></button></p>
                    <p>{{ op.office }}</p>
                </div>
            </div>
        </div>

Upvotes: 1

Views: 912

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50798

The model bound to the select cannot be the same as the element in the store serving the arrays, in this case you have v-model="workloadLevels" and `v-for="wl in workloadLevels".

You're going to need a separate model for the selected value:

v-model="selectedWorkloadLevel"

And create that property selectedWorkloadLevel in your Vuex store.

I would not make an action, just a mutation, and I would make it generic:

SET_VALUE: function(state, payload) {
  Object.keys(payload).forEach((key) => {
    if (state.hasOwnProperty.call(key)) {
      state[key] = payload[key]
    }
  })
}

Then add a get and set computed value for your selectedWorkloadLevel:

get selectedWorkloadLevel() {
  return this.$store.getters['selectedWorkloadLevel']
}

set selectedWorkloadLevel(value) {
  this.$store.commit('SET_VALUE', { selectedWorkloadLevel: value })
} 

Then remove the @change handler and update your v-model:

v-model="selectedWorkloadLevel"

Upvotes: 1

Related Questions