index.js 5.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import VueRouter from 'vue-router'

import {
  isPage
fxy060608's avatar
fxy060608 已提交
5
} from 'uni-helpers/index'
fxy060608's avatar
fxy060608 已提交
6 7 8 9 10 11 12 13 14

import {
  createAppMixin
} from './app'

import {
  createPageMixin
} from './page'

fxy060608's avatar
fxy060608 已提交
15 16 17 18
import {
  lifecycleMixin
} from './lifecycle'

fxy060608's avatar
fxy060608 已提交
19 20 21 22
import {
  initPolyfill
} from './polyfill'

23 24 25 26
import {
  getTabBarScrollPosition
} from './app/router-guard'

雪洛's avatar
雪洛 已提交
27 28 29 30
import {
  uniIdMixin
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
function getMinId (routes) {
  let minId = 0
  routes.forEach(route => {
    if (route.meta.id) {
      minId++
    }
  })
  return minId
}

function getHash () {
  const href = window.location.href
  const index = href.indexOf('#')
  return index === -1 ? '' : decodeURI(href.slice(index + 1))
}

function getLocation (base = '/') {
  let path = decodeURI(window.location.pathname)
49 50 51 52 53 54 55
  const search = window.location.search
  const hash = window.location.hash
  // 检查和纠正 path
  if (base[base.length - 1] === '/' && path === base.substring(0, base.length - 1)) {
    path = base
    window.history.replaceState({}, '', base + search + hash)
  }
fxy060608's avatar
fxy060608 已提交
56 57 58
  if (base && path.indexOf(base) === 0) {
    path = path.slice(base.length)
  }
59
  return (path || '/') + search + hash
fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72
}

/**
 * Service 层 Vue 插件
 * 1.init keepAliveInclude?
 * 2.init router
 * 3.init entryRoute
 * 4.hack vue _init (app)
 * 5.use router
 */
export default {
  install (Vue, {
    routes
fxy060608's avatar
fxy060608 已提交
73
  } = {}) {
74 75 76 77 78 79 80 81 82 83
    if (
      __PLATFORM__ === 'h5' &&
      Vue.config.devtools &&
      typeof window !== 'undefined' &&
      window.navigator.userAgent.toLowerCase().indexOf('hbuilderx') !== -1
    ) {
      // HBuilderX 内置浏览器禁用 devtools 提示
      Vue.config.devtools = false
    }

fxy060608's avatar
fxy060608 已提交
84
    initPolyfill(Vue)
fxy060608's avatar
fxy060608 已提交
85

fxy060608's avatar
fxy060608 已提交
86
    lifecycleMixin(Vue)
87

雪洛's avatar
雪洛 已提交
88 89
    uniIdMixin(Vue)

fxy060608's avatar
fxy060608 已提交
90 91 92 93
    /* eslint-disable no-undef */
    if (typeof __UNI_ROUTER_BASE__ !== 'undefined') {
      __uniConfig.router.base = __UNI_ROUTER_BASE__
    }
fxy060608's avatar
fxy060608 已提交
94 95 96 97 98 99 100 101 102 103
    const minId = getMinId(routes)
    const router = new VueRouter({
      id: minId,
      mode: __uniConfig.router.mode,
      base: __uniConfig.router.base,
      routes,
      scrollBehavior (to, from, savedPosition) {
        if (savedPosition) {
          return savedPosition
        } else {
104 105
          if (
            to &&
fxy060608's avatar
fxy060608 已提交
106 107 108
            from &&
            to.meta.isTabBar &&
            from.meta.isTabBar
109 110 111 112 113 114
          ) { // tabbar 跳 tabbar
            const position = getTabBarScrollPosition(to.params.__id__)
            if (position) {
              return position
            }
          }
fxy060608's avatar
fxy060608 已提交
115 116 117 118 119 120 121 122 123 124 125 126
          return {
            x: 0,
            y: 0
          }
        }
      }
    })
    const keepAliveInclude = []

    // 需跨平台,根据用户配置 hash 或 history 来调用
    const entryRoute = router.match(__uniConfig.router.mode === 'history' ? getLocation(__uniConfig.router.base)
      : getHash())
fxy060608's avatar
fxy060608 已提交
127

fxy060608's avatar
fxy060608 已提交
128 129 130 131 132 133 134 135 136 137 138
    if (entryRoute.meta.name) {
      if (entryRoute.meta.id) {
        keepAliveInclude.push(entryRoute.meta.name + '-' + entryRoute.meta.id)
      } else {
        keepAliveInclude.push(entryRoute.meta.name + '-' + (minId + 1))
      }
    }

    /* eslint-disable no-undef */
    if (__PLATFORM__ === 'h5') {
      if (entryRoute.meta && entryRoute.meta.name) {
fxy060608's avatar
fxy060608 已提交
139 140 141 142 143
        document.body.className = 'uni-body ' + entryRoute.meta.name
        if (entryRoute.meta.isNVue) {
          const nvueDirKey = 'nvue-dir-' + __uniConfig.nvue['flex-direction']
          document.body.setAttribute('nvue', '')
          document.body.setAttribute(nvueDirKey, '')
fxy060608's avatar
fxy060608 已提交
144
        }
fxy060608's avatar
fxy060608 已提交
145 146 147 148 149 150 151 152 153 154 155 156
      }
    }

    Vue.mixin({
      beforeCreate () {
        const options = this.$options
        if (options.mpType === 'app') {
          options.data = function () {
            return {
              keepAliveInclude
            }
          }
157
          const appMixin = createAppMixin(Vue, routes, entryRoute)
fxy060608's avatar
fxy060608 已提交
158 159
          // mixin app hooks
          Object.keys(appMixin).forEach(hook => {
160 161 162
            options[hook] = options[hook] ? [].concat(appMixin[hook], options[hook]) : [
              appMixin[hook]
            ]
fxy060608's avatar
fxy060608 已提交
163 164 165 166 167 168
          })

          // router
          options.router = router

          // onError
fxy060608's avatar
fxy060608 已提交
169 170
          if (!Array.isArray(options.onError) || options.onError.length === 0) {
            options.onError = [function (err) {
fxy060608's avatar
fxy060608 已提交
171
              console.error(err)
fxy060608's avatar
fxy060608 已提交
172
            }]
fxy060608's avatar
fxy060608 已提交
173 174 175 176 177
          }
        } else if (isPage(this)) {
          const pageMixin = createPageMixin()
          // mixin page hooks
          Object.keys(pageMixin).forEach(hook => {
fxy060608's avatar
fxy060608 已提交
178 179 180 181 182 183 184 185 186
            if (options.mpOptions) { // 小程序适配出来的 vue 组件(保证先调用小程序适配里的 created,再触发 onLoad)
              options[hook] = options[hook] ? [].concat(options[hook], pageMixin[hook]) : [
                pageMixin[hook]
              ]
            } else {
              options[hook] = options[hook] ? [].concat(pageMixin[hook], options[hook]) : [
                pageMixin[hook]
              ]
            }
fxy060608's avatar
fxy060608 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
          })
        } else {
          if (this.$parent && this.$parent.__page__) {
            this.__page__ = this.$parent.__page__
          }
        }
      }
    })

    Object.defineProperty(Vue.prototype, '$page', {
      get () {
        return this.__page__
      }
    })

202 203 204 205 206 207 208 209
    Vue.prototype.createSelectorQuery = function createSelectorQuery () {
      return uni.createSelectorQuery().in(this)
    }

    Vue.prototype.createIntersectionObserver = function createIntersectionObserver (args) {
      return uni.createIntersectionObserver(this, args)
    }

210 211 212 213
    Vue.prototype.createMediaQueryObserver = function createMediaQueryObserver (args) {
      return uni.createMediaQueryObserver(this, args)
    }

fxy060608's avatar
fxy060608 已提交
214 215 216
    Vue.use(VueRouter)
  }

217
}