什么是Vuex
Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用了集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。通俗讲可以将它看成把多个组件共享的变量全部存储在一个对象里面,然后,将这个对象放在顶层的vue实例中,让其他组件可以使用。
使用场景
大型单页应用。用户登录状态,用户名称,地理位置,商品的收藏,购物车中的商品。
安装使用
安装使用vuex
npm install vuex --save
一般在src下创建文件夹store,创建index.js文件,文件结构如下
import Vue from 'vue'
import Vuex from 'vuex'
// 1.安装插件
Vue.use(Vuex)
//2.创建对象
const store = new Vuex.store({
state: {},
mutations: {},
actions: {},
getters: {},
modules: {}
})
//3.导出store
export default store
vuex的核心概念
State (单一状态树 Single Source of Truth)
一个项目中最好只创建一个store,单一状态树可以让我们以最直接的方式找到某个状态的片段,在之后的调试中也会非常方便去管理和维护。
Getters
类似于computed,可以对state中的数据进行操作。
默认参数state,还有一个参数为getters
//页面引入
<h1>{{$store.getters.more20stu}}</h1>
<h1>{{$store.getters.more20stunum}}</h1>
<h1>{{$store.getters.moreAgestu(16)}}</h1>
//index.js
students:[
{
name:'kebe',
age: '24',
},
{
name: 'james',
age: '37',
}, {
name: 'curry',
age: '18',
},
{
name: 'harden',
age: '24',
}
]
getters: {
more20stu(state) {
return state.students.filter(s=> s.age>=20)
},
more20stunum(state,getters) {
return getters.more20stu.length
},
moreAgestu(state) {
return function(age) {
return state.students.filter(s => s.age> age)
}
}
},
Mutation
vuex中store状态更新的唯一方式:提交mutation
主要包括两部分:
字符串的事件类型(type)
一个回调函数(handler),该回调函数的第一个参数为state
//mutation的定义方式
mutations: {
increment(state){
state.count++
}
}
//通过mutation更新
add: function () {
this.$store.commit('increment')
}
mutation传递参数
在通过mutation更新数据的时候,有时希望携带一些额外参数。
参数被称为是mutation的载荷(payload)
//单个参数时
incrementn(state,n) {
state.counter += n
},
incrementn() {
this.$store.commit('incrementn',5)
}
//多个参数
//以对象的形式传递
addStu(state,stu) {
state.students.push(stu)
}
addStu() {
const stu = {name: 'allen', age:'36'}
this.$store.commit('addStu',stu)
}
mutation的提交风格
//普通的提交方式
incrementn() {
this.$store.commit('incrementn',5)
},
//包含type属性的对象的提交方式
incrementn() {
this.$store.commit({
type: 'incrementn',
count: 5
})
},
incrementn(state,payload) {
state.counter += payload.count
},
mutation的响应规则
store中state是响应式的,state中数据发生变化,vue组件自动更新
响应规则
1.提前在store中初始化的属性
2.添加新属性可使用
Vue.set()
用新对象给旧对象重新赋值
message: {
name: 'Lin',
age: '33',
number: '7'
},
mutations: {
update(state,payload) {
//非响应式
// state.message['height'] = payload.height
//方式1
// Vue.set(state.message,'height', payload.height)
//方式2
state.message = {...state.message, 'height': payload.height}
}
}
addmes() {
this.$store.commit({
type: 'update',
height: 191
})
Action
若在mutation中执行异步操作,则devoted则追踪不到数据的改变,所以必须在action中进行
actions: {
aUpdateMessage(context,payload) {
return new Promise((resolve,reject) =>{
setTimeout(() => {
context.commit('update')
resolve()
}, 1000);
})
}
},
updateMessage(){
this.$store.dispatch('aaUpdateMessage','参数').then(res =>{
})
}
Module
当应用非常复杂时,store会变得非常臃肿,为了解决这个问题Vuex允许将store分割成模块(Module),而每个模块拥有自己的state、mutations、actions、getters。
store文件目录
|--store
|--index.js
|--actions.js
|--mutations.js
|--modules
|--index.js