在路由之前在vuejs中添加到模板

时间:2019-02-15 14:28:59

标签: vue.js

我想做这样的事情:

Trackable

基本上,我想在更改路线之前调用一个方法。

我已经用这种方法解决了问题:

<router-link  :to="{name: 'home'}"
              before-enter="fooMethod">
      Click here
</router-link>

但是这种方法的问题在于它没有在HTML中呈现<div @click="pushToRoute()">Click here</div> // Methods pushToRoute(){ this.globalVariable = "changed"; this.$route.push({name: 'home'}) } 属性,因此对SEO毫无帮助。在离开路由之前调用方法时,有什么方法可以实现属性<a href="/">的呈现?

1 个答案:

答案 0 :(得分:1)

您可以在使用in-component navigation guard离开路线之前做一些事情。它具有对this的访问权限,这意味着您可以使用组件中的任何数据,也可以使用商店(同步)修改某些内容,或者读取某些内容以决定是否要通过导航。在您的情况下,您可能想使用beforeRouteLeave

  beforeRouteLeave(to, from, next) {
    this.dummyCounter++;

    if (this.dummyCounter % 4 !== 0) {
      // Stay where we are
      next(from.fullPath);
      return;
    }

    // Always call next to continue, or it will forever stay in limbo
    next();
  }

根据您要完成的工作,您可能需要使用全局导航保护(例如,在进行过渡时,或者如果需要在几页上进行某些操作)。在这种情况下,您将在路由器实例上调用beforeEach并在那里执行魔术操作。

Edit Appending before-route to template in vuejs

相关问题