created()钩两次刷新页面

时间:2019-05-15 16:41:40

标签: vue.js vuejs2

在页面刷新上,由于某些奇怪的原因,所创建的钩子碰巧被调用了两次,但是如果我来自另一条路线则不会发生。

created() {         
    this.$store.dispatch('setInternalComponents',true);
    this.getCurrencies();              
},

您可以在下面找到我的路由器配置:

Vue.use(VueRouter);

const routes = [
  { path: "/", component: Auth },
  { path: "/resetpassword", component: Resetpwd },
  { path: "/forgotpassword", component: Forgotpwd },
  { path: "/firstlogin", component: FirstLogin},
  { 
    path: "/dashboard", 
    component: Dashboard,
    beforeEnter(to,from,next){
        if (store.state.accessToken)
        {
          next()
        }else
          next('/')
    }
  },
  { path: "*", redirect: "/" }
];

export default new VueRouter({
  routes: routes,
  mode: "history"
});

1 个答案:

答案 0 :(得分:0)

我已自行修复此问题。 如果我们在创建/挂接的钩子上更新Vuex存储,它将重新呈现该组件,因此我在routes配置中将beforeEnter事件上的逻辑移开以避免这种行为。

代码更改如下:

{ 
    path: "/dashboard", 
    component: Dashboard,
    beforeEnter(to,from,next){
        if (store.state.accessToken)
        {
          store.dispatch('setInternalComponents',true);
          next()
        }else
          next('/')
    }
  },