M
M
Michael2018-05-30 07:45:02
Vue.js
Michael, 2018-05-30 07:45:02

How to apply reactivity when using Vuex?

We are reworking the application, translating it to Vue.js. After splitting into single-file components, they started using Vuex and the question arose - the beauty of Vue for me is data reactivity.
But Vuex requires the use of mutations, not direct data modification in Vuex. How to be?

Example - the component has a checkbox field, how to make the data in it be output from Vuex and changed in Vuex? Those. was it reactive?

I did this - in the component I kept the tmp variable, which, when initialized in data(), gets the value from the Vuex state object and is associated with the checkbox via v-model.
And on the change event, a method is called that changes the Vuex object depending on the state of this temporary variable.

<input type="checkbox" change ="changePrintTwoActs" v-model="tmpActsPrintPages">

data() {
            return {                
                tmpActsPrintPages: this.$store.state.app.actsPrintPages==2 ? true : false
            }
        },
        methods: {
            changePrintTwoActs : function () {
                this.$store.state.app.actsPrintPages = this.tmpActsPrintPages ? 2 : 1;
....

I think it's a crutch. What is the best way to use Vue reactivity when using Vuex?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2018-05-30
@sibidor

Make a computed property whose getter returns a value from vuex, and the setter pulls the mutation:

сomputed: {
  checked: {
    get() {
      return this.$store.state.checked
    },
    set(val) {
      this.$store.commit('updateChecked', val)
    }
  }
}

https://jsfiddle.net/4nkh119u/

A
Andrey Sedyshev, 2018-05-30
@ musikant777

In addition to the above, I can add a link to a fairly good Vuex course:
https://vueschool.io/courses/vuex-for-everyone

A
Anton Anton, 2018-05-30
@Fragster

If you don't like vuex, then there are alternatives, starting with a simple container https://ru.vuejs.org/v2/guide/state-management.htm... and ending with a large list on github

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question