1、新建仓库文件
在store的文件夹中新建一个模块,比如user.js。
模块由3个部分组成:state, mutations, actions。
export const state = {
name: "123"
};
export const mutations = {};
export const actions = {};
2、获取仓库数据
获取vuex的数据通过this.$store.state/模块名/属性名
this.$store.state.user.name
数据渲染
{{$store.state.user.name}}
3、同步修改数据
vuex定义了修改state的数据必须要通过mutations方法来修改(主要是为了可以在函数封装修改的逻辑)
export const state = {
name: "123"
};
export const mutations = {
// 第一个参数必须是state, 第二个参数是传递进来的数据
setName(state, data){
state.name = data;
}
};
组件中调用mutations的方法,第二个参数就是传递的数据
// this.$store.commit("模块名/方法名")
this.$store.commit("user/setName","123")
4、保存store数据到本地中
现在用户已经保存到store了,但是还有一个问题,数据是保存在缓存中的,如果页面一刷新,那么数据就会不见了,这样是不合理的。所以我们需要使用localStorage 把数据保存到本地,但是由于nuxt.js是运行在服务器的,不能直接在store 中使用浏览器的方法,所以我们需要依赖一些判断和插件。
vuex-persistedstate,该插件会把本地存储的数据读取到store。
- 安装插件
npm install --save vuex-persistedstate
- 在根目录plugins 中新建文件localStorage.js,加入以下代码
具体可参考文档地址:https://github.com/robinvdvleuten/vuex-persistedstate#createpersistedstateoptions
import createPersistedState from 'vuex-persistedstate'
export default ({store}) => {
window.onNuxtReady(() => {
createPersistedState()(store)
})
}
- 在nuxt.config.js文件中引入文件
plugins:[
{ src:'@/plugins/localStorage.js',ssr:false}
]
5、异步修改state的数据
// 异步修改state的数据,存放公共的请求函数,并且该函数可能会修改state的数据(不一定要修改)
export const actions = {
// 登录函数可能会复用,会多个地方调用到,刚好该函数请求完成后修改state中userInfo
login(store, data){
// 登录接口提交, (必要要添加return)
return this.$axios({
url: "/accounts/login",
method: "POST",
data
}).then(res => {
// 登录成功后返回上一个页面
this.$router.back();
// 调用user下的mutations的方法
store.commit("setUserInfo", res.data);
return true;
})
}
}
调用
// 提交登录
handleLoginSubmit() {
// validate方法是elementui给el-form表单提供验证的函数
// valid代表验证是否通过
this.$refs["form"].validate(valid => {
if(!valid) return;
// 调用actions的登录方法
this.$store.dispatch("user/login", this.form).then(res => {
if(res === true){
this.$message.success("登录成功,返回上一个页面");
}
})
});
}