new-Vue中router或者store什么时候使用

2次阅读

共计 813 个字符,预计需要花费 3 分钟才能阅读完成。

const app = new Vue({
  router,
  store
}).$mount('#app')

上面实例话 vue 对象时为什么可以传入的 router 和 store 对象,在什么时候使用呢

保存的位置

new vue 其实是调用源码中下面的方法

function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}

也就是说 router 和 store 这种参数是保存在 options 参数中的。

使用

在 vue-router 源码的 install 方法中有如下代码

  Vue.mixin({beforeCreate () {if (isDef(this.$options.router)) {
        this._routerRoot = this
        this._router = this.$options.router
        this._router.init(this)
        Vue.util.defineReactive(this, '_route', this._router.history.current)
      } else {this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
      }
      registerInstance(this, this)
    },
    destroyed () {registerInstance(this)
    }
  })

在 VUE root component 中可以通过 this.$options.router 取到 new vue 传入的 options 对象

这里还有一个技巧
如何使所有子组件都取到 vue 跟组件初始化的对象,比如这里的 this._routerRoot。关键是 this.$parent

正文完
 0