Vuex的基本用法
1.安装Vuex
npm install Vuex@3 # @3 指定 vuex 3版本
# 或 yarn add Vuex@3
2.引入Vuex
创建文件:/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 注册 Vuex 插件
Vue.use(Vuex)
//准备actions对象——响应组件中用户的动作
const actions = {}
//准备mutations对象——修改state中的数据
const mutations = {}
//准备state对象——保存具体的数据
const state = {}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
在main.js中创建vm时传入store配置项
import Vue from 'vue'
import App from './App.vue'
import store from "./store";
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store
}).$mount('#app')
3.基本使用
import Vue from 'vue'
import Vuex from 'vuex'
// 注册 Vuex
Vue.use(Vuex)
const actions = {
add(context,value){
// context:里面包含 dispatch、state、context 等属性
// 这里调用了 mutations 中的 ADD 方法。
context.commit('ADD', value)
},
}
const mutations = {
ADD(state, value){
state.sum += value
}
}
//初始化数据
const state = {
sum: 0
}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
组件读取 vuex 的 state 值:
$store.state.sum
组件中修改vuex中的数据:
$store.dispatch('action中的方法名',"数据")
// 或 $store.commit('mutations中的方法名',数据)
// 若没有网络请求或其他业务逻辑,组件中可以跳过 actions,直接调用 commit
4.getters的使用
类似于组件中的 computed 功能。
const getters = {
total(state){
return state.sum * 10
}
}
//创建并暴露store
export default new Vuex.Store({
......
getters
})
组件中读取数据:$store.getters.total
5.四个map方法的使用
- state
computed: {
// 对象写法
...mapState({sum: 'sum', school: 'school', subject: 'subject'}),
// 数组写法
...mapState(['sum','school','subject']),
},
- getters
computed: {
// 对象写法
...mapGetters({bigSum:'bigSum'}),
// 数组写法
...mapGetters(['bigSum'])
},
- actions
methods:{
// 对象写法
...mapActions({incrementOdd:'add'})
// 数组写法
...mapActions(['add'])
}
- mutations
methods:{
// 对象写法
...mapMutations({increment:'ADD'}),
// 数组写法
...mapMutations(['ADD']),
}
6.模块化
const countAbout = {
namespaced: true,//开启命名空间
state:{ x:1 },
mutations: { ... },
actions: { ... },
getters: {
total(state){
return state.sum * 10
}
}
}
const personAbout = {
namespaced: true,//开启命名空间
state:{ ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
countAbout,
personAbout
}
})
- state
//方式一:
this.$store.state.personAbout.list
//方式二:
...mapState('countAbout',['sum','school','subject']),
- getters
//方式一:
this.$store.getters['personAbout/firstPersonName']
//方式二:
...mapGetters('countAbout',['bigSum'])
- dispatch
//方式一: 调用 personAbout 的 addPersonWang 方法
this.$store.dispatch('personAbout/addPersonWang',person)
//方式二: 调用 countAbout 下 的 add 方法
...mapActions('countAbout',{incrementOdd:'add'})
- commit
//方式一:调用 personAbout 的 ADD_PERSON 方法
this.$store.commit('personAbout/ADD_PERSON', person)
//方式二:调用 countAbout 下 的 ADD 方法
...mapMutations('countAbout',{increment:'ADD'}),