【问题标题】:How to access store getter updated value from main.js file in vue app?如何从 vue 应用程序中的 main.js 文件访问存储 getter 更新值?
【发布时间】:2023-04-11 07:42:01
【问题描述】:

我正在尝试从main.js 文件访问更新的 vuex getter 以检查用户是否已登录。基于此,我将用户带到登录页面。在 main.js 文件中,我只是像这样访问 store getter。

var router = new VueRouter({...})

router.beforeEach((to, from, next) => {
    console.log(store.getters['general/isUserLoggedIn'])
    next()
})

general 是模块名称。

但是当简单地记录 store 时,它会显示具有更新值的对象。但是在记录store.getters['general/isUserLoggedIn'] 时,它会显示初始状态值。为什么它不提供更新的价值。这是正确的做法还是有其他替代方法。

更多细节

store.js 文件中

import Vue from 'vue'
import Vuex from 'vuex'
import general from './modules/general'
import other from './modules/other'

Vue.use(Vuex)

export const store = new Vuex.Store({
    modules: {
        general,
        other
    },
    plugins: [],
    strict: process.env.NODE_ENV !== 'production'
})

通过调用api状态检查用户是否登录 在 App.vue 文件中

axios.get('/api/profile').then((response) => {
    if (response.data.status === 'success') {
        this.setUserLoggedIn(true)
    }
})

actions.js 在通用模块中

setUserLoggedIn ({ commit }, data) {
    commit(types.SET_USER_LOGGED_IN, data)
}

mutations.js 在通用模块中

const mutations = {
    [types.SET_USER_LOGGED_IN](state, data) {
        state.isUserLoggedIn = data
    }
}

【问题讨论】:

  • 如何注册和导入store
  • 在 main.js 中导入存储像这样import { store } from './store'@Mr.

标签: javascript vue.js vuejs2 vuex vue-router


【解决方案1】:

在初始导航中,在警卫中登录尚未完成,这就是您在控制台中看不到该值的原因。它仅在记录 store 时出现 true,因为它是在记录后不久设置的,并且当您记录对象/数组然后单击以查看其属性时,控制台会自行更新。

解决竞争条件的一种方法是在登录完成后重定向到主页:

axios.get('/api/profile').then((response) => {
  if (response.data.status === 'success') {
    this.setUserLoggedIn(true)
    this.$router.push('/');  // Route to home page once login is complete
  }
})

在此之前,如果用户未登录,则重定向到登录:

router.beforeEach((to, from, next) => {
  const isLoggedIn = store.getters['general/isUserLoggedIn'];
  if(!isLoggedIn) {
    return next('/login');
  }
  next()
})
  • 在初始加载时,用户将被重定向到登录页面。
  • 登录完成后,它们将被发送回主页。

【讨论】:

  • 还有next() 进入else 条件,对吗?
  • 不客气。是的,你可以把它放在else 声明中,或者它也可以按照我展示的方式工作。如果条件为真,则函数调用next('login') 并以return 退出,否则将进入下一行调用next
猜你喜欢
  • 2018-12-01
  • 2021-07-16
  • 2013-07-31
  • 2020-12-14
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多