Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js Vue3-使用beforeRouteEnter防止内容闪烁_Vue.js_Axios_Vue Component_Passport.js_Vue Router - Fatal编程技术网

Vue.js Vue3-使用beforeRouteEnter防止内容闪烁

Vue.js Vue3-使用beforeRouteEnter防止内容闪烁,vue.js,axios,vue-component,passport.js,vue-router,Vue.js,Axios,Vue Component,Passport.js,Vue Router,我将Vue与axios一起使用,就像 [...] import VueAxios from "vue-axios"; import axios from "@/axios"; createApp(App) .use(store) .use(router) .use(VueAxios, axios) .mount("#app"); [...] 它在全球范围内非常有效,就像this.axios…无处不在。我还使用Pas

我将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/进行身份验证
,以检查用户是否登录

为了使这项工作,我想使用beforeRouteEnter导航卫士,但不幸的是,我不能在那里调用它

现在我有一个在安装钩,这感觉不对。有没有办法让我的代码保持整洁

请给我一个提示。谢谢

编辑:这对我有用

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;
            }
          }
        });
    });
通过将回调传递给
next
,可以访问组件实例。因此,不要使用
this.axios
,而是使用以下命令:

路由之前(到、从、下一个){ 下一步(vm=>{ console.log(vm.axios);//`vm`是实例 }) } 下面是一个带有异步请求的伪示例。我更喜欢async/await语法,但这样可以更清楚地了解发生了什么:

路由之前(到、从、下一个){ 常量url=https://jsonplaceholder.typicode.com/posts'; // ✅ 路由尚未更改,仍在查看最后一个视图 get(url)。然后(res=>{ // ✅ 异步请求完成,仍然没有更改视图 //现在以某种方式测试结果 如果(res.data.length>10){ //通过测试。继续进行路由 下一步(vm=>{ vm.myData=res.data;//在加载组件之前设置属性 }) }否则{ //不喜欢结果,重定向 下一个(“/”) } }) }
我可以问一下关于我的上述代码的评论吗?.then()中不需要任何内容?我的意思是它可以工作,我不确定它是否应该是这样。有时我的受保护路由的布局会在重定向到我的登录页面之前闪烁。这就是我希望通过导航防护来阻止的。你可以删除
。然后如果你不需要它的话。但我看不出这段代码对任何事情都有什么帮助,因为它进行了axios调用,但对它没有任何作用。而且
返回false
不应中止导航,您应使用
next()
转到其他路线