【问题标题】:how to access the router object in nuxt.js如何访问 nuxt.js 中的路由器对象
【发布时间】:2018-01-06 19:24:57
【问题描述】:

我正在使用基于 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>

【问题讨论】:

  • 您的错误是什么?您能否包含一些代码示例,您是如何尝试从您的组件中访问它的?

标签: javascript vuejs2 frontend nuxt.js


【解决方案1】:

您可以通过this 访问它:

this.$route.path

【讨论】:

  • 我在组件(.vue 文件)中的 &lt;script&gt;&lt;/script&gt; 标签中尝试了 console.log(this.$route),但它报告它未定义!
  • &lt;script&gt; import store from '~/store/index' console.log(store) console.log(this) export default { } &lt;/script&gt;
  • 啊,是的,这行不通。路由对象位于您的组件/页面/布局数据对象中。因此,您可以像访问任何其他数据(如 this.mydata)一样访问它。因此,您必须将日志记录移动到您的组件/页面/布局对象中才能处于正确的范围内。如果你想在组件渲染时立即记录它,你可以把它放在挂载的钩子中,比如 export default { mount () { console.log(this.$route) }}
【解决方案2】:

Nuxt 的做法是使用以下任一方法:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      但需要注意的是:

      $nuxt在初始化完成之前是无法访问的,所以需要在初始化后使用这个方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-02
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 2019-04-24
        • 2020-05-11
        • 1970-01-01
        • 2020-01-15
        相关资源
        最近更新 更多