首页 > 解决方案 > Vue:如何在 Vuex getter 中使用 Per-Route Guard?

问题描述

类似于我们处理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')

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

标签: javascriptvue.jsvue-componentvuexvue-router

解决方案


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

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

推荐阅读