【问题标题】:Vue3 - Using beforeRouteEnter to prevent flashing contentVue3 - 使用 beforeRouteEnter 防止闪烁的内容
【发布时间】:2021-05-04 22:33:20
【问题描述】:

我正在使用 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-endpoint .../api/is-authenticated 来检查用户是否已登录。

为了完成这项工作,我想使用 beforeRouteEnter-navigation 守卫,但不幸的是我不能在那里调用它。

现在我正在安装挂钩,感觉不对。有什么解决方案可以让我的代码保持直截了当吗?

我很感激一个提示。谢谢。

编辑:这对我有用。

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;
            }
          }
        });
    });

【问题讨论】:

    标签: vue.js axios vue-component passport.js vue-router


    【解决方案1】:

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

    beforeRouteEnter (to, from, next) {
      next(vm => {
        console.log(vm.axios);    // `vm` is the instance
      })
    }
    

    这是一个异步请求的伪示例。我更喜欢 async/await 语法,但这会让发生的事情更清楚:

    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('/')
        }
      })
    }
    

    【讨论】:

    • 我可以询问关于我上面代码的评论吗? .then() 中不需要什么?我的意思是它有效,我不确定它是否应该是那样的。
    • 有时我的受保护路由的布局在重定向到我的登录页面之前会闪烁。这是我希望通过导航守卫来防止的。
    • 如果您不需要.then,您可以删除它。但是我看不到代码对任何事情都有什么帮助,因为它进行了 axios 调用,但什么也没做。另外return false 不应该中止导航,你应该使用next() 去另一条路线
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2013-08-04
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多