uniapp-vuex的学习
长时间保存用户的登录状态,app的缓存有时间限制,所以想学习一下用vuex来存储
官方文档
网址
main.js
import Vue from 'vue'
import Antd from 'ant-design-vue';
import App from './App'
import store from './store/'
import 'ant-design-vue/dist/antd.css';
import router from './router'
Vue.config.productionTip = false
Vue.use(Antd);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
登录封装:
import store from '@/store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
const user = {
state: {
userId: '',
token: '',
name: '',
welcome: '',
avatar: '',
roles: [],
buttons: [], // 按钮权限
info: {},
loginname:''
},
mutations: {
SET_TOKEN: (state, token) => {
console.log("token",token);
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_ROLES: (state, roles) => {
state.roles = roles
},
SET_INFO: (state, info) => {
state.info = info
},
SET_BUTTONS: (state, buttons) => {
state.buttons = buttons
},
SET_LOGINNAME: (state, loginname) => {
state.loginname = loginname
},
SET_USERID: (state, userId) => {
console.log("111111",userId);
state.userId = userId
}
},
actions: {
// 登录
// Login ({ commit }, userInfo) {
// return new Promise((resolve, reject) => {
// login(userInfo).then((res) => {
// if (res.data.code == 200) {
// window.localStorage.setItem('token',res.data.token)
// this.$store.commit('SET_TOKEN', res.data.token)
// } else {
// this.$message.error(res.data.msg)
// }
// resolve(res)
// }).catch(error => {
// reject(error)
// })
// })
// },
// 获取用户信息
// GetInfo ({ commit }) {
// return new Promise((resolve, reject) => {
// loginInfo(state.token).then((res)=>{
// // console.log("userInfo:",res)
// commit('SET_ROLES', result.data.roleIds)
// commit('SET_USERID', result.data.userId)
// commit('SET_NAME', result.data.userName)
// commit('SET_LOGINNAME',result.data.loginName)
// window.localStorage.setItem('userInfo',JSON.stringify(res.data))
// console.log("loginName:",state.loginname)
// resolve(res)
// }).catch(error => {
// reject(error)
// })
// })
// },
// 登出
Logout ({ commit, state }) {
return new Promise((resolve) => {
logout(state.token).then(() => {
resolve()
}).catch(() => {
resolve()
}).finally(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
commit('SET_INFO', {})
store.remove(ACCESS_TOKEN)
})
})
}
}
}
export default user
// 设置缓存
window.localStorage.setItem('token',res.data.token)
this.resToken = window.localStorage.getItem("token");
window.localStorage.removeItem("token");
记录一下代码
index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
Vue.use(Vuex);//vue的插件机制
//Vuex.Store 构造器选项
const store = new Vuex.Store({
modules:{
user
}
})
export default store
user.js:
import {INCREMENT,DECREMENT} from './mutations-types'
const user={
//存放全局状态变量
state:{
count:0
},
//修改全局状态变量,一定要在mutations里面
mutations:{
//mutations里面的常量名,一般需要统一设置管理
//一般大写
//存放在mutations-types.js文件中
INCREMENT(state){
state.count +=1
},
DECREMENT(state){
state.count -=1
}
},
//对状态进行包装/过滤什么的
getters:{
myCount(state){
return `count is ${state.count}`
}
},
//状态的业务逻辑
actions:{
myIncrease(context){
context.commit('increment')
},
myDecrease(context){
context.commit('decrement')
}
}
}
export default user
mutations-types.js:
export default {
INCREMENT:'INCREMENT',
DECREMENT:'DECREMENT'
}
newvuex.vue:
<template>
<view>
<view class="">
{{count}}
</view>
<view class="">
{{myCount}}
</view>
<!-- 第一种,直接调用mutations里面的方法-->
<button type="default" @click="INCREMENT">增加--increment</button>
<!-- 第二种,通过别的方法调用,可以再加别的功能 -->
<button type="default" @click="increase">增加--increase</button>
<!-- 直接调用actions里面的方法 -->
<button type="default" @click="decrease">减少---decrease</button>
</view>
</template>
<script>
import{mapState,mapGetters} from "vuex";
import{mapMutations,mapActions} from "vuex";
export default{
name:"aee",
computed:{
//第一种--给 mapState 传一个字符串数组
// ...mapState(['count']),
//第二种--从state中拿到数据 箭头函数可使代码更简练
// ...mapState({
// count:state=>state.user.count
// }),
//为了能够使用 this 获取组件自己的data数据,必须使用常规函数
...mapState({
count(state){
return 'count is'+state.user.count
}
}),
...mapGetters(['myCount'])
},
methods:{
...mapMutations(['INCREMENT'],['DECREMENT']),
...mapActions(['myIncrease'],['myDecrease']),
increase(){
this.$store.commit('INCREMENT')
},
//不知道为什么,这段代码会报错
decrease(){
this.myDecrease()
}
}
}
</script>
<style>
</style>
#如何在组件里使用vuex的数据