Vue.js: how to change a $state of Vuex that is in a v-model?

Asked

Viewed 303 times

2

I am with the following doubt, I have some inputs linked to Vuex states:

<input class="form-control" type="search" placeholder="Filtre sua pesquisa" v-model="$store.state.controlAccessModule.filters.search" v-on:keyup.enter="loadEmployees()" />

But by Vuex standards, I shouldn’t change $state directly by the v-model, how should I do that? Using a $state in the v-model is an "anti Pattern"?

1 answer

3


You need to create a mutation in his store, one mutation is used to update a value in state:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    username: ""
  },
  mutations: {
    setName(state, username) {
      state.username = username;
    }
  }
});

export default store;

Done that, you can use a computed with getter and setter to update the value:

export default {
  computed: {
    username: {
      get() {
        return this.$store.state.username;
      },
      set(value) {
        this.$store.commit("setName", value);
      }
    }
  }
};

Example: https://codesandbox.io/s/loving-swirles-twkw0?fontsize=14&hidenavigation=1&theme=dark

Browser other questions tagged

You are not signed in. Login or sign up in order to post.