Vue-router: Typescript error accessing this.$router.options

Created on 7 Feb 2018  ·  8Comments  ·  Source: vuejs/vue-router

Version

3.0.1

Reproduction link

https://github.com/peterssonanton/vue-example

Steps to reproduce

npm run build

Gives this error:
ERROR Failed to compile with 2 errors 08:25:37

error in /Users/antonpetersson/my-project/src/views/Home.vue

(25,30): Property 'options' does not exist on type 'VueRouter'.

error in /Users/antonpetersson/my-project/src/views/Home.vue

(26,25): Property 'options' does not exist on type 'VueRouter'.

What is expected?

The options property exists on VueRouter, if running 'npm run serve' the app starts (with typescript errors still) and is working.

What is actually happening?

Typescript is giving a compilation error


The example repo is created with the vue-cli: https://github.com/vuejs/vue-cli with only a few lines added code in Home.vue to reproduce the error

Most helpful comment

Works for me

import VueRouter, {
  RouterOptions,
} from 'vue-router';

class VueRouterExtended extends VueRouter {
  options?: RouterOptions
}

All 8 comments

AFAIK, $router.options is a private api so we don't include it in typings.

Maybe I misunderstood then, but is there no way to get the routes from the router object? ($router.options.routes)

You can put them into a variable and export that variable around instead.

Sorry, my mistake. Thanks for the help

Sorry, my mistake. Thanks for the help

You can put them into a variable and export that variable around instead.

Emm, what if I am a plugin maker? I meen I am providing components, and I cannot hope user to pass their options to me?

Besides I also notice that lots of plugin are using this private api, such as antd and vuepress.

So I can only bypass it using an ugly cast?

My solution was to make a separate file for the page routes like this;

export default [{
  path: 'users/:user?',
  name: 'Users'
  component: () => import(/* webpackChunkName: "main" */ '../views/Pages/Users.vue')
}, {
  path: 'organizations/:organization?',
  name: 'Organizations',
  component: () => import(/* webpackChunkName: "main" */ '../views/Pages/Organizations.vue')
}]

Then when I need to access the pages I do this;

import pageRoutes from '@/router/pages'

export default class Navbar extends Vue {
  get pages () {
    return pageRoutes
  }
}

Works for me

import VueRouter, {
  RouterOptions,
} from 'vue-router';

class VueRouterExtended extends VueRouter {
  options?: RouterOptions
}
Was this page helpful?
0 / 5 - 0 ratings