Vue simple application state management vuex

Since scattered across multiple states in every corner of the interaction between many components and large-scale application complexity is growing constantly. To solve this problem, Vue offers vuex

vuex Flowchart:

vuex

【installation】

npm install vuex --save

  In a modular packaging system, you must be explicitly by  Vue.use() installing Vuex

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

Vue.use(Vuex)

  When using the global script tag references Vuex, does not require more installation

[Overview]

  The heart of every Vuex application is to store (warehouse). "Store" is basically a vessel, which contains most of the state of the application (state). Vuex and simple global objects have a different following two points:

  1, Vuex state memory is responsive to. When the component reads Vue state from the store, the store if the state changes, the respective components will be updated accordingly to obtain high

  2, can not directly change the state of the store. The only way to change the status of the store is explicitly commit (commit) mutation. This makes it easy to track changes in each state, making it possible to achieve some tools to help better understand the application

 

The following give a simple counter small chestnut:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment: state => state.count++,
    decrement: state => state.count--,
  }
})
new Vue({
  el: '#app',
  computed: {
    count () {
      return store.state.count
    }
  },
  // view
  template: `
  <div>
    <input type="button" value="-" @click="decrement">
    <span>{{count}}</span>
    <input type="button" value="+" @click="increment">
  </div>
  `,
  // actions
  methods: {
    increment () {
      store.commit('increment')
    },
    decrement () {
      store.commit('decrement')
    },    
  }
})

By  store.state acquiring state objects, as well as by the  store.commit method of triggering a state change of the manner mutation, rather than a direct change  store.state.count, because you want to track changes more clearly to state. This simple agreement allows intent more obvious, so when reading the code easier to interpret changes in the internal state of the application. In addition, this also has the opportunity to achieve some can record every change of state, save a snapshot of the state of debugging tools. With it, you can achieve even as time shuttle-like debugging experience.

  Since the state store is responsive to the state to store the call simple calculation need only be returned to the property in the component. Trigger change is only submitted mutation in the component's methods

 

 

This is a simple understanding of what works and then saying vuex detailed point see the official documents, I will try to finish updating

Guess you like

Origin www.cnblogs.com/tdtdttd/p/11084884.html