vuex + Vue.ls双重数据组合使用,避免数据刷新丢失步骤。

1:vuex存储数据流程

首先先把数据存到vuex,因为我们是在这里存取数据的

  1. 首先定义你要用的数据(可以是变量、对象、数组等)这里拿对象“userinformation”来说,(我这里是给对象定义好了参数,并赋值了初值,你也可以之定义对象)。
const user = {
  state: {
    userinformation:{
      seatId:'',
      seatName:'',
      seatNo:'',
      tenantId:'',
      userId:''
    },

  },

在这里插入图片描述

  1. 然后在mutations方法中书写赋值方法(此方法不对外开放,只能通过actions方法中的方法进行调用)
mutations: {
    SET_USERINFORMATION:(state,ccSeatInfo) => { 
      if(ccSeatInfo != undefined && ccSeatInfo != null){
        state.userinformation.userId = ccSeatInfo.userId 
        state.userinformation.seatId = ccSeatInfo.seatId 
        state.userinformation.seatName = ccSeatInfo.seatName 
        state.userinformation.seatNo = ccSeatInfo.seatNo  
        state.userinformation.tenantId = ccSeatInfo.tenantId 
      }
    }
   }

在这里插入图片描述

  1. 在actions方法中书写对外开放调用方法,用于调用mutations方法中的方法在state中定义的变量赋值。
actions: {
    UserInformation({ commit } ,ccSeatInfo){
      commit('SET_USERINFORMATION',ccSeatInfo)
    },

在这里插入图片描述

  1. 页面赋值(通过…mapActions([“把你在actions中写好的方法在页面按需引入”]))
 ...mapActions([
         "UserInformation"
        ]
      ),

通过this.方法名(调用方法赋值)

this.UserInformation(res.result.ccSeatInfo)
  1. 页面取值
this.$store.state.user.userinformation

2:通过Vue.ls保存数据,赋值到vuex

为什么要用Vue.ls呢:因为Vue.ls保存数据可以设置时间,保存数据方便,取数据不方便,而vuex存取数据都挺方便的,但是浏览器刷新数据就清空了。所以两个结合就保证了数据的有效性。

  1. 首先定义一个常量(我定义在这里src\store\mutation-types.js)
export const USER_INFORMATION = 'Login_User_Information'

在这里插入图片描述

  1. 在main引入并赋值(src\main.js)
import {
    USER_INFORMATION
} from '@/store/mutation-types'

在这里插入图片描述

new Vue({
    router,
    store,
    mounted () {
        store.commit('SET_USERINFORMATION', Vue.ls.get(USER_INFORMATION))
    },
    render: h => h(App)
}).$mount('#app')

在这里插入图片描述

  1. 在getter引入并赋值
import {USER_INFORMATION} from "@/store/mutation-types" 

在这里插入图片描述

const getters = {
  userinformation: state =>{state.user.userinformation = Vue.ls.get(USER_INFORMATION);return state.user.userinformation},
}

export default getters

在这里插入图片描述

  1. 页面引入、赋值
  import {USER_INFORMATION } from "@/store/mutation-types"
  import Vue from 'vue'
Vue.ls.set(USER_INFORMATION, res.result.ccSeatInfo, 7 * 24 * 60 * 60 * 1000); 

3:这样你刷新浏览器,数据就不会丢失了

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值