Vue:如何在 Vuex getter 中使用 Per-Route Guard?

Posted

技术标签:

【中文标题】Vue:如何在 Vuex getter 中使用 Per-Route Guard?【英文标题】:Vue: How to use Per-Route Guard with Vuex getter? 【发布时间】:2021-03-25 15:18:13 【问题描述】:

类似于我们使用isAuthenticate 函数检查用户是否已正确验证的方式,我正在尝试在我的商店中进行检查。

const state = 
    cliente: []
;

const getters = 
    //Verificar Regra
    CHECK_CLIENTE_STATE: (state) => 
        return state.cliente
    


const actions = 
    FETCH_DADOS( commit , obj) 
        return fetch(`http://localhost:3030/pessoas/informacao/$obj['data']`)
            .then(response => response.json())
            .then(data => commit('SetCliente', data))
            .catch(error => console.log(`Fetch: $error`))
    


const mutations = 
    SetCliente(state, cliente) 
        state.cliente = cliente
    

登录页面,

  methods:
    fetch()
      this.$store.dispatch("FETCH_DADOS",'data':'12345')
      this.$router.push('/') 
    
  

在第一次获取点击时,我检查了 Vuex,显然它正在工作。

路线:

const routes = [
        path: '/',
        beforeEnter: (to, from, next) => 
            if (store.getters.CHECK_CLIENTE_STATE == '') 
                next('/login')
            
            next();
        ,
        component: () =>
            import ('../views/Home')
    ,
    
        path: '/login',
        component: () =>
            import ('../views/Login')
    
]

嗯,console.log 在第一次获取点击时,我收到了这个错误,但是在 vuex 中如上所示,存储已满。

未捕获(承诺中)错误:从“/login”转到时重定向到 “/”通过导航守卫。

为什么只是在第二次点击时重定向到home,而不是在第一次?

更新中

在 router.js 中尝试新方法

path: '/',
beforeEnter: (to, from, next) => 
    console.log(!store.getters.CHECK_CLIENTE_STATE.length)
    if (!store.getters.CHECK_CLIENTE_STATE.length) 
        next('/login')
    
    next();
,
component: () =>
    import ('../views/Home')

但同样,第一个获取是 TRUE,第二个是 FALSE,在第二个中我被重定向到 /home

【问题讨论】:

dispatch() 返回一个承诺。承诺解决后更改路线:this.$store.dispatch("FETCH_DADOS",'data':'12345').then(() => this.$router.push('/'))。那时,它已经提交了SetCliente 【参考方案1】:

路由器在数据加载之前被定向。等待它:

methods:
  async fetch()
    await this.$store.dispatch("FETCH_DADOS",'data':'12345')
    this.$router.push('/') 
  

【讨论】:

以上是关于Vue:如何在 Vuex getter 中使用 Per-Route Guard?的主要内容,如果未能解决你的问题,请参考以下文章

Vue:如何在 Vuex getter 中使用 Per-Route Guard?

Firestore、vue、vuex、vuexfire:如何让 getter 真正从存储中获取数据?

Vue 单元测试:如何使用 props、vuex store、watchers、getter 等测试复杂组件

从模板访问 vue vuex 命名空间的 getter

如何在 Vuex 4 和 TypeScript 中使用其他存储模块 getter/actions/mutations

vuex的使用