简介
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
如果代码中没有大量的重复操作和数据, vuex可以不去使用。一般情况在报存用户数据及重复操作时使用
Vue2
-
需要引入Vue和Vuex 还需要使用Vue.use(Vuex)。在main.js 需要引入 store 然后将store注册一下。
然后就可以进行编写vuex的代码了
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
content:'学习vuex'
}
})
设置全局访问的state对象,需要啥状态就放进去啥
使用 this.$store.state.content 获取值
- getters
getter实际上与computed类似
可以在vuex中监听state值的变化
getters:{
getContent(state)
return state.count
}
可以使用 this.$store.getters.getCount 获取值
- mutations
如果要修改store值的唯一方法就是通过mutation来修改
在store内 添加mutations方法
mutations:{
update(state,num)
state.context = num
}
使用update
methods:{
updateContext(){
this.$store.commit('update','111')
}
}
-
actions
actions类似于mutations,单不能直接修改状态需要通过mutations提交修改状态
actions可以进行异步操作创建一个actions
actions:{
updateContext(context,num){ //假设 异步操作
context.commit('update',num)
}
}
业务代码
需要使用 dispatch进行提交
methods:{
add(){
this.$store.dispatch('updateContext',1)
}
}
- 辅助函数
mapState、mapGetters、mapActions
如果觉得上面的写法比较繁琐就可以使用辅助函数进行代替。
使用方法
//html代码
<span>{{this.$store.state.context}}</span>
<button @click="update(111)">点击增加total</button>
import{mapState,mapGetters,mapActions,mapMutations} from'vuex'
export default {
computed:{
...mapState({
num:state=>state.content,
})
},
methods:{
...mapMutation({
update:'update' //update是Mutations对应的方法名,可以设置一个其他key
})
...mapActions({
updateDemo:"updateContext" //设置一个别名
})
//调用todosAlise 得到return返回值
...mapGetters({
todosAlise:'getToDo'
})
},
created:{
//this.$store.dispatch('updateContext',1) 直接通过store触发dispatch 改变state值
this.updateDemo() // 通过mapActions 触发mutations 从而改变state值
}
}
vue3.x
vue3中的vuex没有太多的变化
引入时需要从vuex导入createStore
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
使用vuex也发生了一些改变
import { defineComponent } from 'vue'
import { useStore } from 'vuex';
export default defineComponent({
setup () {
// 需要创建一个 store 变量
const store = useStore();
// 再使用 store 去操作 Vuex 的 API
// ...
}
})