账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Vue无法在加载时读取cookies并加载到Vuex的store中
    42
    0

    问题描述

    我在使用Vue开发一个应用的前端,想要实现同时使用vuex的store和cookies来保存用户的登录信息,我的实现方法是:用户登录后将用户信息和isLogin字段保存在vuex的store以及cookies里面,然后vue-router跳转到用户后台,(vue-router验证vuex的store中isLogin字段是否为true来判断用户的登录态);在Vue加载时(mounted)我也写了将相关cookies读取并写入store的函数,但是每次刷新后这个并没有生效,所以总是要求用户重新登录。想知道应该怎么修改?谢谢大家!

    相关代码

    1. main.js中Vue的初始化:
    new Vue({
        el: '#app',
        router,
        store,
        components: { App },
        template: '<App/>',
        mounted: function () {
            if (getCookie(isLogin)) {//getCookie等函数是我自己写的,应该没有问题
                this.$store.commit('account/setuser', getCookie('user'))
            } else {
                this.$store.commit('account/logout')
            }
        }
    })
    2. vuex的store中有关部分
    export default {
      namespaced: true,
      state: {
        user: {},
        isLogin: false
      },
      mutations: {
        login (state, user) {//登录时调用的函数
          state.user = user
          state.isLogin = true
    
          setCookie('user', user)
          setCookie('isLogin', true)
      },
    
        logout (state) {//注销时调用的函数
            state.user = {}
            state.isLogin = false
    
            removeCookie('user')
            setCookie('isLogin', false)
        }
      }
    }
    3. vue-router中有关登录态的判断
    router.beforeEach((to, from, next) => {
      //判断要去的路由有没有requiresAuth
      if(to.meta.requiresAuth){//需要认证
        if(store.state.account.isLogin == true){
          next();
        }else{
          next({
            path: '/login',
            query: { redirect: to.fullPath } 
          });
        }
    
    }else if (to.meta.requiresNoAuth) {//需要不认证
        if(store.state.account.isLogin == false){
          next();
        }else{
          next({
            path: '/'
          });
        }
    }{
        next();
      }
    });
    0
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • 漫步あ雨中 普通会员 1楼

      Vue无法在加载时读取cookies并加载到Vuex的store中,是因为Vue并没有提供这样的功能。Vue的store是用来存储状态的,它不会保存用户的浏览器 cookie。

      如果你需要在加载时读取浏览器的 cookie,你可以使用Vue的内置方法navigator.cookieService。这个方法可以用来读取和设置 cookie。

      如果你需要在Vuex的store中存储这些 cookie,你可以使用Vuex的cookie选项,它会将这些 cookie 存储到 Vuex store 中。

      以下是一个简单的示例:

      ```javascript import Vue from 'vue' import Vuex from 'vuex'

      Vue.use(Vuex)

      const store = new Vuex.Store({ state: { cookie: {} }, mutations: { setCookie(value) { store.commit('SET_COOKIE', value) } }, actions: { setCookie({ commit }, value) { commit('SET_COOKIE', value) } } }) ```

      在这个示例中,我们首先导入了 Vue 和 Vuex。然后,我们创建了一个新的 Vuex store,并设置了它的 state、mutations 和 actions。最后,我们定义了 setCookie 和 setCookie 的 actions,这两个 action 可以用来读取和设置 cookie。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部