我将Vue与axios一起使用,如
[...]
import VueAxios from "vue-axios";
import axios from "@/axios";
createApp(App)
.use(store)
.use(router)
.use(VueAxios, axios)
.mount("#app");
[...]它在全球范围内运作得非常好,比如this.axios...无处不在。我还使用Passport进行身份验证,在我受保护的路由中,我想调用我的Express端点.../api/is-authenticated来检查用户是否已登录。
为了使这一工作,我想使用前unfortunately导航警卫,但不幸的是,我不能在那里调用它。
现在我被装在钩子里,感觉不对。有什么解决方案让我的代码保持清晰吗?
我希望你能给我个提示。谢谢。
编辑:这对我有用。
beforeRouteEnter(to, from, next) {
next((vm) => {
var self = vm;
self
.axios({ method: "get", url: "authenticate" })
.then() //nothing needed here to continue?
.catch((error) => {
switch (error.response.status) {
case 401: {
return { name: "Authentification" }; //redirect
//break;
}
default: {
return false; //abort navigation
//break;
}
}
});
});发布于 2021-01-31 15:50:53
使用beforeRouteEnter,可以通过将回调传递给next来访问组件实例。因此,不要使用this.axios,而是使用以下方法:
beforeRouteEnter (to, from, next) {
next(vm => {
console.log(vm.axios); // `vm` is the instance
})
}下面是一个包含异步请求的伪示例。我更喜欢异步/等待语法,但这将使所发生的事情更加清晰:
beforeRouteEnter(to, from, next) {
const url = 'https://jsonplaceholder.typicode.com/posts';
// ✅ Routing has not changed at all yet, still looking at last view
axios.get(url).then(res => {
// ✅ async request complete, still haven't changed views
// Now test the result in some way
if (res.data.length > 10) {
// Passed the test. Carry on with routing
next(vm => {
vm.myData = res.data; // Setting a property before the component loads
})
} else {
// Didn't like the result, redirect
next('/')
}
})
}https://stackoverflow.com/questions/65981018
复制相似问题