The 10 minute vuex

Vuex global unified state management, problem solving and data sharing status communications between components.

first step

store.js

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

Vue.use(Vuex) // 使用插件
// 导出store实例
export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  }
})
复制代码

The second step

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store, // 增加store属性,值是导出store的实例
  render: h => h(App)
}).$mount('#app')

复制代码

By the above two steps, each component has a $storeproperty, that is the container we created. There are commit, dispatch, state, getters, actions, mutations, in each component can this.$storelook at the print out.

start using

Defined state

export default new Vuex.Store({
  state: {
	count: 1 // state中定义响应式的数据
  }
})
复制代码

Use state : store in a statedefined state count, may be used in the assembly this.$store.state.countacquired.


Defined mutations

In the store of mutationsthe method of adding the corresponding

export default new Vuex.Store({
  state: {
	count: 1 // state中定义响应式的数据
  },
  mutations: {
	addTen (state, num) {
		state.count = state.count + num
	}
  },
  actions: {

  }
})
复制代码

Submit mutations assembly by commitsubmission mutationsto modify the statestate

this.$store.commit('addTen', 10)
复制代码

Actions defined in the store of actionsthe method of adding the corresponding

export default new Vuex.Store({
  state: {
	count: 1
  },
  mutations: {
	addTen (state, num) {
		// 第一个参数是状态,第二个是传入的参数
		state.count = state.count + num
	}
  },
  actions: {
	minusTen ({commit}, num) {
		// 第一个参数是store实例,第二个是传入的参数
		setTimeout(() => {
			commit('addTen', num)
		}, 1000)
	}
  }
})
复制代码

Action distribution component that can be used dispatchto distribute an action to trigger the actionsmethod, actionsmay submit asynchronous mutationsto modify statestate

this.$store.dispatch('minusTen', 10)
复制代码

actionsMainly multiplexing, the package code, asynchronous processing, the request interface, etc., into the modified state of the real mutationsprocessing


Getters is defined in the store of gettersthe method of adding the corresponding

export default new Vuex.Store({
  state: {
	count: 1,
	person: {
		name: '张三'
	}
  },
  getters: {
	getName (state) {
		// getters是同步的
		return state.person.name
	}
  }
})
复制代码

Use getters

this.$store.getters.getName
复制代码

gettersThe method defined corresponding to the calculated attributes defined in corresponding to computedthe same, there is, dependency changes recalculated.

Component code demo

<template>
  <div class="hello">
    <h1>{{ this.$store.state.count }}</h1>
    <h1>{{ this.$store.getters.getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
export default {
  methods: {
    syncAdd () {
      this.$store.commit('addTen', 10)
    },
    asyncAdd () {
      this.$store.dispatch('minusTen', 10)
    }
  }
}
</script>
复制代码

Logogram

The above are written in the this.$storeget property methods or operation.

this.$store.state.count
this.$store.getters.getName
this.$store.commit('addTen', 10)
this.$store.dispatch('minusTen', 10)
复制代码

But these operations are more complicated to write, write every time this.$store, for shorthand, so vuex provides methods map directly into components ready to use.

<template>
  <div class="hello">
    <h1>{{ count }}</h1>
    <h1>{{ getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
import {mapActions, mapState, mapMutations, mapGetters} from 'vuex'
export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['getName'])
  },
  methods: {
    syncAdd () {
      this.addTen(10)
    },
    asyncAdd () {
      this.minusTen(10)
    },
    ...mapActions(['minusTen']),
    ...mapMutations(['addTen'])
  }
}
</script>
复制代码

One thing to be noted that, using extended operator, represents all objects returned by these methods, mapStateand mapGettersto define attributes in the calculation because they are defined in response to the data type. While mapActionsand mapMutationswe need to be defined in the methods of.

Split module

Condition can be hierarchical, when a project too much maintenance state, can be split into individual modules, there is a store in the definition of the modulesproperties, which can define separate module.

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

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    'page1': {
      namespaced: true,
      state: {
        count: 1,
        person: {
          name: '张三'
        }
      },
      mutations: {
        addTen (state, num) {
          state.count = state.count + num
        }
      },
      actions: {
        minusTen ({commit}) {
          setTimeout(() => {
            commit('addTen', 10)
          }, 1000)
        }
      },
      getters: {
        getName (state) {
          return state.person.name
        }
      }
    }
  }
})
复制代码

So used in the assembly

<template>
  <div class="hello">
    <h1>{{ count }}</h1>
    <h1>{{ getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
import {mapActions, mapState, mapMutations, mapGetters} from 'vuex'
export default {
  computed: {
    ...mapState('page1', ['count']),
    ...mapGetters('page1', ['getName'])
  },
  methods: {
    syncAdd () {
      this.addTen(10)
    },
    asyncAdd () {
      this.minusTen(10)
    },
    ...mapActions('page1', ['minusTen']),
    ...mapMutations('page1', ['addTen'])
  }
}
</script>
复制代码

Each method pass two parameters, the first parameter specifies a namespace, the second parameter is the corresponding attributes in order to further abbreviations may be specified by the namespace helper function module specified in the current component.

<template>
  <div class="hello">
    <h1>{{ count }}</h1>
    <h1>{{ getName }}</h1>
    <button @click="syncAdd">同步加10</button>
    <button @click="asyncAdd">异步加10</button>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
// 创建帮助函数指定命令空间
let { mapActions, mapState, mapMutations, mapGetters } = createNamespacedHelpers('page1')

export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['getName'])
  },
  methods: {
    syncAdd () {
      this.addTen(10)
    },
    asyncAdd () {
      this.minusTen(10)
    },
    ...mapActions(['minusTen']),
    ...mapMutations(['addTen'])
  }
}
</script>
复制代码

Do not use abbreviations

this.$store.getters['page1/getName']
this.$store.state.page1.count
this.$store.commit('page1/addTen', 10)
this.$store.dispatch('page1/minusTen', 10)
复制代码

Reproduced in: https: //juejin.im/post/5cf78624f265da1b9421383b

Guess you like

Origin blog.csdn.net/weixin_34396103/article/details/91444508