Decouple Vuex, use modules to build Vuex

A lot of people at work asked this question:

My input box V-model is bound to state in Vuex, but there is no two-way binding. Today we will talk about how to bind Vuex gracefully

– The first (stream of violence)

<div> <input type="text" v-model="$store.state.Root.value" /> <p>{{ $store.state.Root.value }}</p> // I'm using modules from vuex. I'll introduce modules in a new article. </div>Copy the code
  • We all know v-model is a syntactic sugar:

      <input type="text" v-model="val" />
    Copy the code

    Is equivalent to

      <input type="text" :value="value" @input="value = $event.tagret.value" />
    Copy the code
  • In fact, the first method is to use the grammar sugar of V-model. As for why mutations are not necessary, I guess it is because of the reference relationship of the object

– Second (elegant, through computed)

  • This method has always been recommended by me in the team, because it complies with the core concept of Vuex: use mutations to change state
  • <input v-model="getVal" /> computed: { getVal: {get() {return this.$store.state.root. value}; set(newVal) { this.$store.commit('handleVal', newVal) } } }Copy the code
  • Computed actually accepts two parameters:
    • Get: Triggered when a value is obtained
    • Set: Triggered when a value is modified and a new value is returned as an argument

– So I get Vuex in get

– Call mutations in set

  •  // store.js
     mutations: {
         handleVal(state, payload) {
             state.value = payload
         }
     }
    Copy the code

I put the demo on Github