Home > Article > Web Front-end > Installation and use of Vue.js state management mode Vuex (code example)
The content of this article is about the installation and use of Vue.js state management mode Vuex (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
uex 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.
First we install vuex in the vue.js 2.0 development environment:
npm install vuex --save
Then, add:
import vuex from 'vuex' Vue.use(vuex); const store = new vuex.Store({//store对象 state:{ show:false, count:0 } })
to main.js and then Then, add the store object when instantiating the Vue object:
new Vue({ el: '#app', router, store,//使用store template: '<app></app>', components: { App } })
Now, you can obtain the state object through store.state and trigger state changes through the store.commit method:
store.commit('increment') console.log(store.state.count) // -> 1
The easiest way to read the state from the store instance is to return a certain state in the calculated property:
// 创建一个 Counter 组件 const Counter = { template: `<p>{{ count }}</p>`, computed: { count () { return this.$store.state.count } } }
When a component needs to obtain multiple states, declaring these states as computed properties will be somewhat repetitive and redundant. In order to solve this problem, we can use the mapState auxiliary function to help us generate calculated properties:
// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from 'vuex' export default { // ... computed: mapState({ // 箭头函数可使代码更简练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count', // 为了能够使用 `this` 获取局部状态,必须使用常规函数 countPlusLocalState (state) { return state.count + this.localCount } }) }
When the name of the mapped calculated property is the same as the name of the child node of state, we can also pass a string array to mapState :
computed: mapState([ // 映射 this.count 为 store.state.count 'count' ])
Getters are similar to computed in vue. They are used to calculate state and then generate new data (state). Just like calculated properties, the return value of getter will It is cached based on its dependencies and will only be recalculated when its dependency values change.
Getter accepts state as its first parameter:
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
The Getter is exposed as a store.getters object, and you can access these values as properties :
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter can also accept other getters as the second parameter:
getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length } } store.getters.doneTodosCount // -> 1
Used in components:
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } }
Note that getters are used as Vue when accessed through properties Part of a reactive system is caching.
You can also pass parameters to the getter by letting the getter return a function. It is very useful when you query the array in the store:
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } }
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
Note that when the getter is accessed through a method, it will be called every time without caching the results.
mapGetters auxiliary function just maps the getters in the store to local calculated properties:
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
If you want to give a getter property another name, Use object form:
mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
The only way to change the state in the Vuex store is to submit a mutation.
Registration:
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { // 变更状态 state.count++ } } })
Call:
store.commit('increment')
You can pass in additional parameters to store.commit, that is, mutation Payload:
// ... mutations: { increment (state, n) { state.count += n } }
store.commit('increment', 10)
If multiple parameters are submitted, they must be submitted in the form of objects
// ... mutations: { increment (state, payload) { state.count += payload.amount } }
store.commit('increment', { amount: 10 })
Note: The operations in mutations must be synchronous;
Action is similar to mutation, except that
Action submits a mutation instead of directly changing the state.
Action can contain any asynchronous operation.
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })
Action is triggered through the store.dispatch method:
store.dispatch('increment')
Execute asynchronous operations inside the action:
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
Pass parameters in object form:
// 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 })
Related recommendations:
Vue.js of vuex (state management)
How to use Vuex state management
About Vuex’s family bucket status management
The above is the detailed content of Installation and use of Vue.js state management mode Vuex (code example). For more information, please follow other related articles on the PHP Chinese website!