Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。原理图如下:
Vuex 可以帮助我们管理共享状态,并附带了更多的概念和框架。这需要对短期和长期效益进行权衡。如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的store 模式就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。
npm安装
npm install vuex --save
yarn 安装
yarn add vuex
在main.js中将vuex挂载到vue中,以便在项目中的任何地方都能使用vuex。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use('Vuex')
Vuex依赖Promise ,IE内核不支持Promise。使用polyfill 的库es6-promise。
npm install es6-promise --save
yarn add es6-promise
在main.js中,引入vuex之前引入es6-promise
import "es6-promise/auto"
查看是否引入成功
console.log(window.Promise) //在IE浏览器中查看是否有Promise对象
import { createApp } from 'vue'
import { createStore } from 'vuex'
// 创建一个新的 store 实例
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
const app = createApp({ /* 根组件 */ })
// 将 store 实例作为插件安装
app.use(store)
state 状态
Getters 计算属性
Mutations 直接更改state状态(同步)
Actions 装饰器,提交Mutations ,间接改变状态(异步)
Module 模块 ,store 多模块。每个模块都有单独的函数
mapState
mapGetters
mapMutaions
mapActions
state是整个应用的数据源,其他几个核心方法都是为了修改state而满足不同需要的。比如说mutaions是同步更新state,actions是异步更新state。掌握上面这几个核心的方法就精通vuex这个库了。下面我来讲解一下核心方法的使用。
获取state 的几种方法。
第一种 直接获取:
this.$store.state.bianliang
第二种 通过助手函数获取:
import {mapState} from 'vuex'
computed:{
...mapState(['total'])
}
使用store.commit() 调用Mutations 里是函数。
//store.js
const store = new Vuex.Store({
state:{
total:1,
username:''
},
mutations:{
Increment(state){
state.total ++
},
UsernameMutations(state ,payload){
state.username = payload.username
}
}
})
//app.vue
export default {
data(){
return {}
},
methods:{
add(){
//同步更新state
this.$store.commit('Increment')
}
}
}
使用store.dispatch() 调用Actions里的函数。
//store.js
const store = new Vuex.Store({
state:{
total:1,
username:""
},
mutations:{
Increment(state){
state.total++
},
UsernameMutations(state ,payload){
//将store的username 更新为payload.uname
state.username = payload.uname
}
}
,actions:{
IncrementAsync(context){
//在action中,使用commit调用mutations的函数
context.commit('Increment')
},
UsernameAsync(context ,payload){
//传payload
context.commit('UsernameMutations',payload)
}
}
})
//app.vue 在组件中调用state
export default {
data(){
return{}
},
methods:{
add(){
this.$store.dispatch('IncrementAsync')
},
setUsername(){
//异步更新state
this.$store.dispatch('UsernameAsync' ,{
username:"admin"
})
}
}
}
modules 创建多个store数据文件。以便管理
// store.js
//引入子模块
import moduleA from './action/a'
import moduleB from './action/b'
const store = new Vuex.Store({
modules:{
a:moduleA,
b:moduleB
}
})
export default store
//a.js
const moduleA = {
state:{
total : 1
},
mutations:{
incrementA(state){
state.total++
}
},
actions:{}
}
//b.js
const moduleB = {
state:{
total:100
},
mutations:{
incrementB(state){
state.total ++
}
},
actions:{}
}
//app.vue
<span>{{$store.a.total}} ~ {{$store.b.total}}</span>
methods:{
add(){
this.$store.commit('incrementA')
this.$store.commit('incrementB')
}
}