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

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

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据