如何在NuxtJs中挂钩beforeRouteEnter

时间:2019-07-11 09:00:36

标签: vue.js nuxt.js

我正在尝试为我的nuxtjs应用获取上一条路由,因此对于我来说,我使用的是beforeRouteEnter,但是beforeRouteEnter并未触发。

我尝试在nuxt-link中添加密钥: 但仍然无法正常工作。.

<nuxt-link :key="$route.path" :to="'/services/'+service.id">

所以这是我的代码:


  created: function(){
    console.log("created");
  },

  mounted: function(){
    console.log("mounted");
  },

  mounted: function(){
    console.log("mounted");
  },

  beforeRouteEnter(to, from, next) {

    console.log("before route called");

    next(vm => {
      console.log("prev rout is: "+vm.prevRoute);
    })

  }

我期望的是:

before route called
prev rout is: /services
created
mounted

但是我只能得到:

created
mounted

我在做错什么吗?

1 个答案:

答案 0 :(得分:0)

在基于nuxt ˆ2.0.0的当前项目中尝试您的代码,从/路径导航到/ _slug路径后,我会向您报告开发工具控制台。

_slug.js:200 before route called
_slug.js:192 created
_slug.js:198 mounted
_slug.js:205 prev rout is: undefined

刷新页面时,_slug相同。

如果您想要上一条路线,为什么不简单地做:

beforeRouteEnter(to, from, next) {
   console.log("before route called");
   const previousRoute = from.path || from.fullPath
   console.log(`Previous Route ${previousRoute}`)
}

哪个日志是:

_slug.js:200 before route called
_slug.js:202 Previous Route /