vue3-route相关源码

175 阅读1分钟

override.js

  const init = Vue.prototype._init
  Vue.prototype._init = function (options) {
    options = options || {}
    const root = options._parent || options.parent || this
    const router = root.$router
    const route = root.$route
    if (router) {
      // expose router
      this.$router = router
      router._children.push(this)
      /* istanbul ignore if */
      if (this._defineMeta) {
        // 0.12
        this._defineMeta('$route', route)
      } else {
        // 1.0
        defineReactive(this, '$route', route)
      }
    }
    init.call(this, options)
  }

link.js

 onClick (e) {
      // don't redirect with control keys
      /* istanbul ignore if */
      if (e.metaKey || e.ctrlKey || e.shiftKey) return
      // don't redirect when preventDefault called
      /* istanbul ignore if */
      if (e.defaultPrevented) return
      // don't redirect on right click
      /* istanbul ignore if */
      if (e.button !== 0) return

      const target = this.target
      if (target) {
        // v-link with expression, just go
        e.preventDefault()
        this.router.go(target)
      } else {
        // no expression, delegate for an <a> inside
        var el = e.target
        while (el.tagName !== 'A' && el !== this.el) {
          el = el.parentNode
        }
        if (el.tagName === 'A' && sameOrigin(el)) {
          e.preventDefault()
          var path = el.pathname
          if (this.router.history.root) {
            path = path.replace(this.router.history.rootRE, '')
          }
          this.router.go({
            path: path,
            replace: target && target.replace,
            append: target && target.append
          })
        }
      }
    },

index.js

go (path) {
    let replace = false
    let append = false
    if (Vue.util.isObject(path)) {
      replace = path.replace
      append = path.append
    }
    path = this.stringifyPath(path)
    if (path) {
      this.history.go(path, replace, append)
    }
  }

htm5.js

    go (path, replace, append) {
    const url = this.formatPath(path, append)
    if (replace) {
      history.replaceState({}, '', url)
    } else {
      // record scroll position by replacing current state
      history.replaceState({
        pos: {
          x: window.pageXOffset,
          y: window.pageYOffset
        }
      }, '', location.href)
      // then push new state
      history.pushState({}, '', url)
    }
    const hashMatch = path.match(hashRE)
    const hash = hashMatch && hashMatch[0]
    path = url
      // strip hash so it doesn't mess up params
      .replace(hashRE, '')
      // remove root before matching
      .replace(this.rootRE, '')
    th

index.js

    this.history = new History({
      root: root,
      hashbang: this._hashbang,
      onChange: (path, state, anchor) => {
        this._match(path, state, anchor)
      }
    })