vuejs typescript property router does not exist

2020-04-11 11:12发布

I try to access router in my typescript class component:

import {Vue} from 'vue-property-decorator'
import Component from 'nuxt-class-component'
import {Getter, Action} from 'vuex-class'

@Component
export default class Login extends Vue {
    @Action login

    username = ''
    password = ''

    async submit () {
        await this.login({username: this.username, password: this.password})
        this.$router.push('/results')
    }
}

Unfortunately, I get:

error TS2339: Property '$router' does not exist on type 'Login'.

3条回答
相关推荐>>
2楼-- · 2020-04-11 11:37

Make sure you have the router imported in your main vue file:

import router from './router'

const v = new Vue({
  router,

  render: h => h(App)
}).$mount('#app')

This is how I write my components, but I think it is the same.

  import Vue from 'vue'

  export default Vue.extend({
    name: 'Login'

  })
查看更多
我命由我不由天
3楼-- · 2020-04-11 11:41

other answer don't work for me

but the code below works

import Vue from 'vue';

import VueRouter from 'vue-router';

...
  public rowClick(row: object, column: object, event: object): void {
      console.log(row, column, event);
      this.$router.push('/login');
  }
...
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-04-11 11:53

Shim the vue file and include $router:

Make a typings file called vue-shim.d.ts

Adjust your shim like this:

import VueRouter, { Route } from 'vue-router'

declare module 'vue/types/vue' {
  interface Vue {
    $router: VueRouter
  }
}

now Vue (in your case -- this) will have a property of $router and typescript won't complain.

查看更多
登录 后发表回答