Simple use of vuex

What is Vuex?

Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue's official debugging tool devtools extension (opens new window), which provides advanced debugging functions such as time travel debugging with zero configuration and import and export of state snapshots.

When should Vuex be used?

Vuex can help us manage shared state with more concepts and frameworks. This requires a trade-off between short-term and long-term benefits.

If you do not intend to develop large single page applications, using Vuex may be cumbersome and redundant. That's true - if the application is simple enough, it's best not to use Vuex. A simple store mode (opens new window) is enough. However, if we need to build a medium and large-scale single page application, we are likely to consider how to better manage the state outside the component, and Vuex will become a natural choice.

1, Install and introduce vuex

npm install vuex --save

Introduce in main.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

2, Build the core warehouse store.js

The state of Vuex application should be stored in store.js. vue components can obtain the state from store.js, which can be understood as a warehouse of global variables. However, there are some differences from simple global variables, mainly reflected in that when the state in the store changes, the corresponding vue components will also be updated efficiently.
Create a store folder in the src directory, and create the store.js file in it:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  namespaced: true,
  state: {
    testContent: 'This is a vuex Global test',
  },
  mutations: {
    // Reset vuex local storage status
    resetStore (state) {
      Object.keys(state).forEach((key) => {
        state[key] = cloneDeep(window.SITE_CONFIG['storeState'][key])
      })
    }
  }
})

A status testContent is stored here.
Although Vue and Vuex have been introduced in main.js, they have to be introduced again.

3, Map state to component

<template>
  <div class="service">
    <div class="conta">
      <span class="impt-remarks">
       	{{testContent}}
      </span>
    </div>
  </div>
</template>
<script>
  export default{
    name:'service-bar',
    computed: {
      testContent(){
      	return this.$store.state.testContent
      }
    }
  }
</script>

The value of testContent will be echoed in the corresponding place.

4, Modify state in component

<template>
  <div class="service">
    <div class="conta">
      <span class="impt-remarks" @click="changeBtn()">
       	{{testContent}}
      </span>
    </div>
  </div>
</template>
<script>
  export default{
    name:'service-bar',
    data(){
      return{
      	testStyle: "111111",
      }
    },
    computed: {
      testContent(){
      	return this.$store.state.testContent
      }
    }
    methods: {
      changeBtn() {
        this.$store.state.testContent = "The changed content is like this"
      }
    }
  }
</script>

5, Use the modification method recommended by vue official

The only way to change the state in Vuex's store is to submit the mutation. The mutation in Vuex is very similar to events: each mutation has a string event type and a callback function (handler). This callback function is where we actually change the state, and it will accept state as the first parameter:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // Change status
      state.count++
    }
  }
})

A mutation handler cannot be called directly. This option is more like event registration: "call this function when a mutation of type increment is triggered." to wake up a mutation handler, you need to call the store.commit method with the corresponding type:

store.commit('increment')

store.js can be written as follows:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  namespaced: true,
  state: {
    testContent: 'This is a vuex Global test',
  },
  mutations: {
    newTest(state, msg) {
      state.testContent = msg
    }
  }
})

First, define a method newTest in store.js, where the first parameter state is $store.state, and the second parameter msg needs to be passed in separately;
Then click the event changeBtn() to modify it

changeBtn(){
  this.$store.commit('newTest', this.testStyle)
}

Use $store.commit to submit a new test, and pass this.testStyle to msg to modify testtest

Keywords: Javascript Vue Vue.js

Added by cpetercarter on Mon, 20 Sep 2021 10:22:12 +0300