一、安装
npm install vuex --save
二、配置
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
// 安装插件
Vue.use(Vuex);
// 创建对象
const store = new Vuex.Store({
state: {
counter: 20
},
mutation: {},
getters: {},
action: {},
modules: {}
});
// 导出
export default store;
// 这个部分不写在main.js中
// 是为了防止以后使用的插件越来越多,导致了main.js中的代码不在清晰可读了
// 所以单独写在一个js文件中再引进这个js的对象就可以更加好的去管理这些插件对象了
三、使用
// main.js
import store from './store'; // 引进来
Vue.prototype.$store = store; // 放到全局对象中
// 使用组件的地方
<template>
<p>{{$store.state.counter}}</p>
</template>
<script>
export default {
data(){
return {}
},
mounted(){
console.log(this.$store.state.counter)
}
}
</script>
四、属性
1、state:状态,即所有的变量
2、mutations:更新state中的变量
(1)唯一能更新state中变量的地方
(2)同步操作的时候调用
(3)参数被称为是mutations的载荷(payload)
// store/index.js
const store = new Vuex.Store({
state:{
counter: 20
},
mutations:{
addOneCounter(){
this.state.counter = 30
},
addCounter(state,payload){
this.state.counter += payload;
},
addOtherWay(state, payload){
state.counter = payload.count++;
}
}
});
// Test.vue
<script>
export default {
mounted(){
// 不建议使用这种方式
this.$store.state.counter++;
// 建议使用以下方式,2种风格
this.$store.commit("addOneCounter");
this.$store.commit("addCounter",10);
this.$store.commit({
type: "addOtherWay",
count: 10
})
}
}
</script>
3、getter:读取数据
(1)一般情况下,调用getters中的方法,不需要带上括号,
包括在标签中、js或者getters的其他函数中
(2)getters本身是不能传递参数的,所以只能通过getters本身去返回一个函数来传递参数
这种情况,调用getters中方法需要带上括号
// store/index.js
const store = new Vuex.Store({
state:{
students: [{},{}]
},
getters:{
getMoreAge(state){
return state.students.filter(item => item.age>15)
},
getMoreAgeLen(state,getters){
return getters.getMoreAge.length
},
getMaxAge(state, getters){
return (max) => {
return state.students.filter(item => item.age>max)
}
// 当这个getters的方法有可能传参,也有可能不传参的话,
// 在没有参数需要传的情况下,也要放个空的括号在调用的地方
},
}
});
// Test.vue
<template>
<div>
<p>{{$store.getters.getMoreAge}}</p>
<p>{{$store.getters.getMaxAge()}}</p>
</div>
</template>
<script>
export default {
mounted() {
const length = this.store.getMoreAgeLen;
const length2= this.$store.getMaxAge(16);
}
}
</script>
4、actions:动作
(1)异步操作时调用
(2)通过 dispatch 方法去调用
// store/index.js
const store = new Vuex.Store({
state:{
counter: 0
},
getters:{
addCount(state, payload){
state.counter += payload.count;
}
},
actions:{
waitMe(context, param){ // param是传递的参数的对象
// 这里用setTimeout模拟延时操作
setTimeout(()=>{
return new Promise((resolve, reject) => {
context.commit({
type: 'addCount',
count: param.count
});
resolve();
})
},1000)
}
},
});
// Test.vue
export default {
mounted() {
this.$store.dispatch('waitMe',{
message:'这是输出信息哈哈哈哈',
count: 20,
}).then(()=>{
console.log('这里已经用promise完成了')
})
}
}
5、modules:模块
(1)在这里可以嵌套多个store格式的json对象(但是里面一般就不会再有modules了,否则会太复杂了),模块中的mutations中的方法名和store中的方法名不要重复,否则在commit的时候没有办法判断是哪一个了
(2)引用模块中的state:{{$store.state.模块名称.变量名}}
(3)引用模块中的getters:{{$store.getters.方法名}}
getters方法中参数可以拿到根store
getter:{
getName(state, getters, rootstate){}
}
(4)模块中actions中的方法有一个特殊参数 context 中有根store的所有东西,这个在根store的actions中是没有的
五、特别的使用
1、vuex-persistedstate:Vuex持久化插件
在页面刷新后,保存指定数据(比如用户信息、token、静态数据的处理等),减少一些接口的调用。vuex-persistedstate 结合了存储方式,在入口统一配置,就不用每次都手动写存储的方法。
(1)安装
npm install --save vuex-persistedstate
(2)配置项
| 参数 | 描述 |
|---|---|
| key | 存储数据的键名。(默认:vuex) |
| paths | 如果没有给出路径,则将保留完整状态;如果给出一个空数组,则不会保留任何状态;如果给出的是state的某个值 或者 某个模块的state的某个值( “xx.xxx” ),则保留所指定的值。 |
| reducer | 缓存reducer返回的值,格式同 paths,reducer优先级高于paths |
| storage | 指定存储数据的方式。默认是localStorage ,也可以设置为 sessionStorage |
| getState | 用来重新补充先前持久状态的功能,默认使用:storage定义获取的方式 |
| setState | 用以保持给定状态的函数。默认使用:storage定义的设置值方式 |
| filter | 一个将被调用以过滤setState最终将在存储中筛选过滤的函数。默认为() => true。 |
(3)使用
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate";
import user from './modules/user'
const persistedArr = [
createPersistedState({
key: 'userInfo',
paths: ['user.userInfo'],
storage: window.sessionStorage
}),
createPersistedState({
key: 'userName',
reducer: state => state.user.userInfo ? state.user.userInfo.name : null,
storage: {
getItem: key => Cookies.get(key),
setItem: (key, value) => Cookies.set(key, JSON.parse(value)),
removeItem: key => Cookies.remove(key)
}
}),
createPersistedState({
key: 'baseInfo',
paths: ['baseInfo'],
storage: window.sessionStorage
}),
];
const store = new Vuex.Store({
state:{
baseInfo:{}
},
getters:{},
modules:{
user
},
plugins: [...persistedArr]
});
本文详细介绍了Vue.js的状态管理库Vuex的安装、配置及使用方法,包括state、mutations、getters、actions和modules等核心概念,并展示了如何利用vuex-persistedstate插件实现Vuex状态的持久化。
864

被折叠的 条评论
为什么被折叠?



