javascript - 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
解决方案
在加载数据之前对路由器进行定向。等待它:
methods:{
async fetch(){
await this.$store.dispatch("FETCH_DADOS",{'data':'12345'})
this.$router.push('/')
}
}
推荐阅读
- javascript - Html / javascript - 下拉选择不适用于提交按钮
- java - 将数据从 Firebase 检索到 Recycler View
- sql - 使用 LIKE %x% 的 Access SQL 查询中出现意外结果
- arrays - 我将如何制作 3D 棋盘阵列
- r - 总结具有不同 nrow 长度组的函数的组
- python - 运行烧瓶项目的问题
- php - 为什么 rtrim 删除尾随零?
- python - 如何让 tkinter mainloop 等待 matplotlib 点击事件
- python - 在 for 循环中从字典中排除项目并将 if 和 else 与字典一起使用
- react-native - 如何在 React Navigation 5 中调用 toggleDrawer