如何访问 nuxt.js 中的路由器对象

how to access the router object in nuxt.js

我正在使用基于 vue.js 的 nuxt.js 开发一个网站。该站点是一个简单的站点,其中包含许多内容页面。我想创建一个组件,它知道它在内容中的位置,因此需要访问路由器对象。我试过 $nuxt.$route.path 但出现错误。如何导入 $nuxt$router 对象以在我的组件中访问它们?

我的模板组件

<template>
  <div>
      <hr>
      <p>{{ $store.state.menuitems[0] }}</p>
      <hr>
      <div class="artfooter">
        <span>i want name of current route here</span>
      </div>
      <br>
  </div>
</template>


<style scoped>
.artfooter{
    font-size: 0.8em;
    display: flex;
    justify-content: space-between;
}
</style>



<script>
  import store from '~/store/index'
  //how to import $nuxt object to access router??
  console.log(store)
  console.log(this.$router.path)
  // the above console.log reports error
  // Cannot read property 'middleware' of undefined

  export default {
  }
</script>

您通过 this 访问它:

this.$route.path

Nuxt 的使用方法如下:

// say that we are in "About Us" page

this.$nuxt.$route.name // returns 'about-us'
this.$nuxt.$route.path // returns '/about-us'

就一般方法而言,我个人认为最好的方法是:

const store = window.$nuxt.$store
const router = window.$nuxt.$router

不过需要注意的是:

$ nuxt cannot be accessed until initialization is complete, so this method needs to be used after initialization.

您也可以通过这种方式从全局 $nuxt 对象访问路由和路由器对象

 this.$nuxt._route
 this.$nuxt._router