首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vue3 -使用beforeRouteEnter防止闪烁内容

Vue3 -使用beforeRouteEnter防止闪烁内容
EN

Stack Overflow用户
提问于 2021-01-31 15:44:15
回答 1查看 3.8K关注 0票数 1

我将Vue与axios一起使用,如

代码语言:javascript
运行
复制
[...]
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导航警卫,但不幸的是,我不能在那里调用它。

现在我被装在钩子里,感觉不对。有什么解决方案让我的代码保持清晰吗?

我希望你能给我个提示。谢谢。

编辑:这对我有用。

代码语言:javascript
运行
复制
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;
            }
          }
        });
    });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-31 15:50:53

使用beforeRouteEnter,可以通过将回调传递给next来访问组件实例。因此,不要使用this.axios,而是使用以下方法:

代码语言:javascript
运行
复制
beforeRouteEnter (to, from, next) {
  next(vm => {
    console.log(vm.axios);    // `vm` is the instance
  })
}

下面是一个包含异步请求的伪示例。我更喜欢异步/等待语法,但这将使所发生的事情更加清晰:

代码语言:javascript
运行
复制
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('/')
    }
  })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65981018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档