前言
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储,管理应用中所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
一、作用
1、进行统一的状态管理,解决不同组件共享数据的问题。
2、不同视图需要变更同一状态的问题。
二、使用
1、安装引入 npm install vuex --save
2、注册到vue中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
3、实例化vuex的store
const store = new Vuex.Store({
state: {
count: 0,
title:'vuex中的title'
},
mutations: {
increment(state,count) {
state.count=count
}
}
})
4、挂载在vue实例上
new Vue({
store
})
5、在组件中就可以通过this.$store对vuex进行操作。
三、核心概念
1、state
2、getters
3、mutations
4、actions
5、modules
1.state
状态的初始化
组件中去取state的值:
1、通过this.$store.state
2、可以通过计算属性取得,mapState辅助函数,可以简化操作
import {mapState} from "vuex";
computed: {
// 可以写一些其他的计算属性
...mapState({
// title: state => state.title
title: "title" //可以直接用title不需要在写$store.state
//title: state => {
//return state.title;
/}
})
}
2.getters
对state中的数据进行初加工(派生)
取getters中的值:
1、通过this.$store.getters
2、通过计算属性取,getters也有辅助函数mapGetters, 用法和mapState一致。
4.import { mapGetters} from "vuex";
5.computed: {
6. // 可以写一些其他的计算属性
7. ... mapGetters ({
8. title: "title"
9. })
10. }
3.mutations
修改state中的值,我们state每次变化,都应该由mutation去修改
const store = new Vuex.Store({
// ....
mutations: {
increment(state, count) {
state.count = count
},
}
})
调用mutations
1、this.$store.commit(‘mutation类型(函数名)’,“参数,参数一般是对象形式”)
2、his.$store.commit({type:‘mutation类型(函数名)’},…其他参数)
mutation函数必须是同步的。
4.actions
action类似于mutation
1、action可以包含异步操作
2、action不能直接修改state,如果想修改state的话,需要触发mutation
actions: {
// 通过context(上下文环境)可以触发mutation,触发action,获取state、getter等操作
// 第二个参数就是我们传递过来的参数
changeTitle(context,payload) {
setTimeout(() => {
context.commit(CHANGE_TITLE, payload)
}, 1000);
}
}
触发action
1、this.$store.dispatch(‘action名字’,‘参数’)
2、this.$store.dispatch({type:‘action类型(函数名)’},…其他参数)
5.modules
1、由于使用单一的状态树,项目中的状态会集中在一起,导致难以维护,这个时候可以通过module对store进行拆分。
2、使用module之后,每个模块都有自己的state、mutation等内容,方便维护
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})