vuejs / vue-router

🚦 The official router for Vue 2
http://v3.router.vuejs.org/
MIT License
18.99k stars 5.06k forks source link

I Can't Use 'Vue.$router' #3815

Closed kimsupin closed 1 year ago

kimsupin commented 1 year ago

Version

3.6.0

Steps to reproduce

import router from './router';

Vue.use(VueRouter);

new Vue({
   router
}).$mount('#app');

console.log(Vue.$router) // undefined

What is expected?

스크린샷 2022-12-27 오후 7 28 55

What is actually happening?

undefined


I check vue-router/install.js

  Object.defineProperty(Vue.prototype, '$router', {
    get () { return this._routerRoot._router }
  })

  Object.defineProperty(Vue.prototype, '$route', {
    get () { return this._routerRoot._route }
  })

I think it's gonna work to write this.

  Object.defineProperty(Vue, '$router', {
    get () { return this._routerRoot._router }
  })

  Object.defineProperty(Vue, '$route', {
    get () { return this._routerRoot._route }
  })

new attributes is need to be assigned Vue, not Vue.property.

LinusBorg commented 1 year ago

Vue.$router is not a thing, there's no such feature/API. The prototype extension is making the router available in all components as this.$router, so that code is fine and correct the way it is.

If you need to access it outside of a compoent, you can do so by either just importing the router instance from where you created it, or accessing Vue.prototype.$router