Router hinzugefügt - funktioniert noch nicht
This commit is contained in:
+202
@@ -0,0 +1,202 @@
|
||||
/* @flow */
|
||||
|
||||
import type VueRouter from './index'
|
||||
import { resolvePath } from './util/path'
|
||||
import { assert, warn } from './util/warn'
|
||||
import { createRoute } from './util/route'
|
||||
import { fillParams } from './util/params'
|
||||
import { createRouteMap } from './create-route-map'
|
||||
import { normalizeLocation } from './util/location'
|
||||
|
||||
export type Matcher = {
|
||||
match: (raw: RawLocation, current?: Route, redirectedFrom?: Location) => Route;
|
||||
addRoutes: (routes: Array<RouteConfig>) => void;
|
||||
};
|
||||
|
||||
export function createMatcher (
|
||||
routes: Array<RouteConfig>,
|
||||
router: VueRouter
|
||||
): Matcher {
|
||||
const { pathList, pathMap, nameMap } = createRouteMap(routes)
|
||||
|
||||
function addRoutes (routes) {
|
||||
createRouteMap(routes, pathList, pathMap, nameMap)
|
||||
}
|
||||
|
||||
function match (
|
||||
raw: RawLocation,
|
||||
currentRoute?: Route,
|
||||
redirectedFrom?: Location
|
||||
): Route {
|
||||
const location = normalizeLocation(raw, currentRoute, false, router)
|
||||
const { name } = location
|
||||
|
||||
if (name) {
|
||||
const record = nameMap[name]
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
warn(record, `Route with name '${name}' does not exist`)
|
||||
}
|
||||
if (!record) return _createRoute(null, location)
|
||||
const paramNames = record.regex.keys
|
||||
.filter(key => !key.optional)
|
||||
.map(key => key.name)
|
||||
|
||||
if (typeof location.params !== 'object') {
|
||||
location.params = {}
|
||||
}
|
||||
|
||||
if (currentRoute && typeof currentRoute.params === 'object') {
|
||||
for (const key in currentRoute.params) {
|
||||
if (!(key in location.params) && paramNames.indexOf(key) > -1) {
|
||||
location.params[key] = currentRoute.params[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (record) {
|
||||
location.path = fillParams(record.path, location.params, `named route "${name}"`)
|
||||
return _createRoute(record, location, redirectedFrom)
|
||||
}
|
||||
} else if (location.path) {
|
||||
location.params = {}
|
||||
for (let i = 0; i < pathList.length; i++) {
|
||||
const path = pathList[i]
|
||||
const record = pathMap[path]
|
||||
if (matchRoute(record.regex, location.path, location.params)) {
|
||||
return _createRoute(record, location, redirectedFrom)
|
||||
}
|
||||
}
|
||||
}
|
||||
// no match
|
||||
return _createRoute(null, location)
|
||||
}
|
||||
|
||||
function redirect (
|
||||
record: RouteRecord,
|
||||
location: Location
|
||||
): Route {
|
||||
const originalRedirect = record.redirect
|
||||
let redirect = typeof originalRedirect === 'function'
|
||||
? originalRedirect(createRoute(record, location, null, router))
|
||||
: originalRedirect
|
||||
|
||||
if (typeof redirect === 'string') {
|
||||
redirect = { path: redirect }
|
||||
}
|
||||
|
||||
if (!redirect || typeof redirect !== 'object') {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
warn(
|
||||
false, `invalid redirect option: ${JSON.stringify(redirect)}`
|
||||
)
|
||||
}
|
||||
return _createRoute(null, location)
|
||||
}
|
||||
|
||||
const re: Object = redirect
|
||||
const { name, path } = re
|
||||
let { query, hash, params } = location
|
||||
query = re.hasOwnProperty('query') ? re.query : query
|
||||
hash = re.hasOwnProperty('hash') ? re.hash : hash
|
||||
params = re.hasOwnProperty('params') ? re.params : params
|
||||
|
||||
if (name) {
|
||||
// resolved named direct
|
||||
const targetRecord = nameMap[name]
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert(targetRecord, `redirect failed: named route "${name}" not found.`)
|
||||
}
|
||||
return match({
|
||||
_normalized: true,
|
||||
name,
|
||||
query,
|
||||
hash,
|
||||
params
|
||||
}, undefined, location)
|
||||
} else if (path) {
|
||||
// 1. resolve relative redirect
|
||||
const rawPath = resolveRecordPath(path, record)
|
||||
// 2. resolve params
|
||||
const resolvedPath = fillParams(rawPath, params, `redirect route with path "${rawPath}"`)
|
||||
// 3. rematch with existing query and hash
|
||||
return match({
|
||||
_normalized: true,
|
||||
path: resolvedPath,
|
||||
query,
|
||||
hash
|
||||
}, undefined, location)
|
||||
} else {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
warn(false, `invalid redirect option: ${JSON.stringify(redirect)}`)
|
||||
}
|
||||
return _createRoute(null, location)
|
||||
}
|
||||
}
|
||||
|
||||
function alias (
|
||||
record: RouteRecord,
|
||||
location: Location,
|
||||
matchAs: string
|
||||
): Route {
|
||||
const aliasedPath = fillParams(matchAs, location.params, `aliased route with path "${matchAs}"`)
|
||||
const aliasedMatch = match({
|
||||
_normalized: true,
|
||||
path: aliasedPath
|
||||
})
|
||||
if (aliasedMatch) {
|
||||
const matched = aliasedMatch.matched
|
||||
const aliasedRecord = matched[matched.length - 1]
|
||||
location.params = aliasedMatch.params
|
||||
return _createRoute(aliasedRecord, location)
|
||||
}
|
||||
return _createRoute(null, location)
|
||||
}
|
||||
|
||||
function _createRoute (
|
||||
record: ?RouteRecord,
|
||||
location: Location,
|
||||
redirectedFrom?: Location
|
||||
): Route {
|
||||
if (record && record.redirect) {
|
||||
return redirect(record, redirectedFrom || location)
|
||||
}
|
||||
if (record && record.matchAs) {
|
||||
return alias(record, location, record.matchAs)
|
||||
}
|
||||
return createRoute(record, location, redirectedFrom, router)
|
||||
}
|
||||
|
||||
return {
|
||||
match,
|
||||
addRoutes
|
||||
}
|
||||
}
|
||||
|
||||
function matchRoute (
|
||||
regex: RouteRegExp,
|
||||
path: string,
|
||||
params: Object
|
||||
): boolean {
|
||||
const m = path.match(regex)
|
||||
|
||||
if (!m) {
|
||||
return false
|
||||
} else if (!params) {
|
||||
return true
|
||||
}
|
||||
|
||||
for (let i = 1, len = m.length; i < len; ++i) {
|
||||
const key = regex.keys[i - 1]
|
||||
const val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i]
|
||||
if (key) {
|
||||
// Fix #1994: using * with props: true generates a param named 0
|
||||
params[key.name || 'pathMatch'] = val
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
function resolveRecordPath (path: string, record: RouteRecord): string {
|
||||
return resolvePath(path, record.parent ? record.parent.path : '/', true)
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
/* @flow */
|
||||
|
||||
import Regexp from 'path-to-regexp'
|
||||
import { cleanPath } from './util/path'
|
||||
import { assert, warn } from './util/warn'
|
||||
|
||||
export function createRouteMap (
|
||||
routes: Array<RouteConfig>,
|
||||
oldPathList?: Array<string>,
|
||||
oldPathMap?: Dictionary<RouteRecord>,
|
||||
oldNameMap?: Dictionary<RouteRecord>
|
||||
): {
|
||||
pathList: Array<string>;
|
||||
pathMap: Dictionary<RouteRecord>;
|
||||
nameMap: Dictionary<RouteRecord>;
|
||||
} {
|
||||
// the path list is used to control path matching priority
|
||||
const pathList: Array<string> = oldPathList || []
|
||||
// $flow-disable-line
|
||||
const pathMap: Dictionary<RouteRecord> = oldPathMap || Object.create(null)
|
||||
// $flow-disable-line
|
||||
const nameMap: Dictionary<RouteRecord> = oldNameMap || Object.create(null)
|
||||
|
||||
routes.forEach(route => {
|
||||
addRouteRecord(pathList, pathMap, nameMap, route)
|
||||
})
|
||||
|
||||
// ensure wildcard routes are always at the end
|
||||
for (let i = 0, l = pathList.length; i < l; i++) {
|
||||
if (pathList[i] === '*') {
|
||||
pathList.push(pathList.splice(i, 1)[0])
|
||||
l--
|
||||
i--
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pathList,
|
||||
pathMap,
|
||||
nameMap
|
||||
}
|
||||
}
|
||||
|
||||
function addRouteRecord (
|
||||
pathList: Array<string>,
|
||||
pathMap: Dictionary<RouteRecord>,
|
||||
nameMap: Dictionary<RouteRecord>,
|
||||
route: RouteConfig,
|
||||
parent?: RouteRecord,
|
||||
matchAs?: string
|
||||
) {
|
||||
const { path, name } = route
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert(path != null, `"path" is required in a route configuration.`)
|
||||
assert(
|
||||
typeof route.component !== 'string',
|
||||
`route config "component" for path: ${String(path || name)} cannot be a ` +
|
||||
`string id. Use an actual component instead.`
|
||||
)
|
||||
}
|
||||
|
||||
const pathToRegexpOptions: PathToRegexpOptions = route.pathToRegexpOptions || {}
|
||||
const normalizedPath = normalizePath(
|
||||
path,
|
||||
parent,
|
||||
pathToRegexpOptions.strict
|
||||
)
|
||||
|
||||
if (typeof route.caseSensitive === 'boolean') {
|
||||
pathToRegexpOptions.sensitive = route.caseSensitive
|
||||
}
|
||||
|
||||
const record: RouteRecord = {
|
||||
path: normalizedPath,
|
||||
regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
|
||||
components: route.components || { default: route.component },
|
||||
instances: {},
|
||||
name,
|
||||
parent,
|
||||
matchAs,
|
||||
redirect: route.redirect,
|
||||
beforeEnter: route.beforeEnter,
|
||||
meta: route.meta || {},
|
||||
props: route.props == null
|
||||
? {}
|
||||
: route.components
|
||||
? route.props
|
||||
: { default: route.props }
|
||||
}
|
||||
|
||||
if (route.children) {
|
||||
// Warn if route is named, does not redirect and has a default child route.
|
||||
// If users navigate to this route by name, the default child will
|
||||
// not be rendered (GH Issue #629)
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (route.name && !route.redirect && route.children.some(child => /^\/?$/.test(child.path))) {
|
||||
warn(
|
||||
false,
|
||||
`Named Route '${route.name}' has a default child route. ` +
|
||||
`When navigating to this named route (:to="{name: '${route.name}'"), ` +
|
||||
`the default child route will not be rendered. Remove the name from ` +
|
||||
`this route and use the name of the default child route for named ` +
|
||||
`links instead.`
|
||||
)
|
||||
}
|
||||
}
|
||||
route.children.forEach(child => {
|
||||
const childMatchAs = matchAs
|
||||
? cleanPath(`${matchAs}/${child.path}`)
|
||||
: undefined
|
||||
addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs)
|
||||
})
|
||||
}
|
||||
|
||||
if (route.alias !== undefined) {
|
||||
const aliases = Array.isArray(route.alias)
|
||||
? route.alias
|
||||
: [route.alias]
|
||||
|
||||
aliases.forEach(alias => {
|
||||
const aliasRoute = {
|
||||
path: alias,
|
||||
children: route.children
|
||||
}
|
||||
addRouteRecord(
|
||||
pathList,
|
||||
pathMap,
|
||||
nameMap,
|
||||
aliasRoute,
|
||||
parent,
|
||||
record.path || '/' // matchAs
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if (!pathMap[record.path]) {
|
||||
pathList.push(record.path)
|
||||
pathMap[record.path] = record
|
||||
}
|
||||
|
||||
if (name) {
|
||||
if (!nameMap[name]) {
|
||||
nameMap[name] = record
|
||||
} else if (process.env.NODE_ENV !== 'production' && !matchAs) {
|
||||
warn(
|
||||
false,
|
||||
`Duplicate named routes definition: ` +
|
||||
`{ name: "${name}", path: "${record.path}" }`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function compileRouteRegex (path: string, pathToRegexpOptions: PathToRegexpOptions): RouteRegExp {
|
||||
const regex = Regexp(path, [], pathToRegexpOptions)
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
const keys: any = Object.create(null)
|
||||
regex.keys.forEach(key => {
|
||||
warn(!keys[key.name], `Duplicate param keys in route with path: "${path}"`)
|
||||
keys[key.name] = true
|
||||
})
|
||||
}
|
||||
return regex
|
||||
}
|
||||
|
||||
function normalizePath (path: string, parent?: RouteRecord, strict?: boolean): string {
|
||||
if (!strict) path = path.replace(/\/$/, '')
|
||||
if (path[0] === '/') return path
|
||||
if (parent == null) return path
|
||||
return cleanPath(`${parent.path}/${path}`)
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
/* @flow */
|
||||
|
||||
import { install } from './install'
|
||||
import { START } from './util/route'
|
||||
import { assert } from './util/warn'
|
||||
import { inBrowser } from './util/dom'
|
||||
import { cleanPath } from './util/path'
|
||||
import { createMatcher } from './create-matcher'
|
||||
import { normalizeLocation } from './util/location'
|
||||
import { supportsPushState } from './util/push-state'
|
||||
|
||||
import { HashHistory } from './history/hash'
|
||||
import { HTML5History } from './history/html5'
|
||||
import { AbstractHistory } from './history/abstract'
|
||||
|
||||
import type { Matcher } from './create-matcher'
|
||||
|
||||
export default class VueRouter {
|
||||
static install: () => void;
|
||||
static version: string;
|
||||
|
||||
app: any;
|
||||
apps: Array<any>;
|
||||
ready: boolean;
|
||||
readyCbs: Array<Function>;
|
||||
options: RouterOptions;
|
||||
mode: string;
|
||||
history: HashHistory | HTML5History | AbstractHistory;
|
||||
matcher: Matcher;
|
||||
fallback: boolean;
|
||||
beforeHooks: Array<?NavigationGuard>;
|
||||
resolveHooks: Array<?NavigationGuard>;
|
||||
afterHooks: Array<?AfterNavigationHook>;
|
||||
|
||||
constructor (options: RouterOptions = {}) {
|
||||
this.app = null
|
||||
this.apps = []
|
||||
this.options = options
|
||||
this.beforeHooks = []
|
||||
this.resolveHooks = []
|
||||
this.afterHooks = []
|
||||
this.matcher = createMatcher(options.routes || [], this)
|
||||
|
||||
let mode = options.mode || 'hash'
|
||||
this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false
|
||||
if (this.fallback) {
|
||||
mode = 'hash'
|
||||
}
|
||||
if (!inBrowser) {
|
||||
mode = 'abstract'
|
||||
}
|
||||
this.mode = mode
|
||||
|
||||
switch (mode) {
|
||||
case 'history':
|
||||
this.history = new HTML5History(this, options.base)
|
||||
break
|
||||
case 'hash':
|
||||
this.history = new HashHistory(this, options.base, this.fallback)
|
||||
break
|
||||
case 'abstract':
|
||||
this.history = new AbstractHistory(this, options.base)
|
||||
break
|
||||
default:
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
assert(false, `invalid mode: ${mode}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match (
|
||||
raw: RawLocation,
|
||||
current?: Route,
|
||||
redirectedFrom?: Location
|
||||
): Route {
|
||||
return this.matcher.match(raw, current, redirectedFrom)
|
||||
}
|
||||
|
||||
get currentRoute (): ?Route {
|
||||
return this.history && this.history.current
|
||||
}
|
||||
|
||||
init (app: any /* Vue component instance */) {
|
||||
process.env.NODE_ENV !== 'production' && assert(
|
||||
install.installed,
|
||||
`not installed. Make sure to call \`Vue.use(VueRouter)\` ` +
|
||||
`before creating root instance.`
|
||||
)
|
||||
|
||||
this.apps.push(app)
|
||||
|
||||
// main app already initialized.
|
||||
if (this.app) {
|
||||
return
|
||||
}
|
||||
|
||||
this.app = app
|
||||
|
||||
const history = this.history
|
||||
|
||||
if (history instanceof HTML5History) {
|
||||
history.transitionTo(history.getCurrentLocation())
|
||||
} else if (history instanceof HashHistory) {
|
||||
const setupHashListener = () => {
|
||||
history.setupListeners()
|
||||
}
|
||||
history.transitionTo(
|
||||
history.getCurrentLocation(),
|
||||
setupHashListener,
|
||||
setupHashListener
|
||||
)
|
||||
}
|
||||
|
||||
history.listen(route => {
|
||||
this.apps.forEach((app) => {
|
||||
app._route = route
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach (fn: Function): Function {
|
||||
return registerHook(this.beforeHooks, fn)
|
||||
}
|
||||
|
||||
beforeResolve (fn: Function): Function {
|
||||
return registerHook(this.resolveHooks, fn)
|
||||
}
|
||||
|
||||
afterEach (fn: Function): Function {
|
||||
return registerHook(this.afterHooks, fn)
|
||||
}
|
||||
|
||||
onReady (cb: Function, errorCb?: Function) {
|
||||
this.history.onReady(cb, errorCb)
|
||||
}
|
||||
|
||||
onError (errorCb: Function) {
|
||||
this.history.onError(errorCb)
|
||||
}
|
||||
|
||||
push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
|
||||
this.history.push(location, onComplete, onAbort)
|
||||
}
|
||||
|
||||
replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
|
||||
this.history.replace(location, onComplete, onAbort)
|
||||
}
|
||||
|
||||
go (n: number) {
|
||||
this.history.go(n)
|
||||
}
|
||||
|
||||
back () {
|
||||
this.go(-1)
|
||||
}
|
||||
|
||||
forward () {
|
||||
this.go(1)
|
||||
}
|
||||
|
||||
getMatchedComponents (to?: RawLocation | Route): Array<any> {
|
||||
const route: any = to
|
||||
? to.matched
|
||||
? to
|
||||
: this.resolve(to).route
|
||||
: this.currentRoute
|
||||
if (!route) {
|
||||
return []
|
||||
}
|
||||
return [].concat.apply([], route.matched.map(m => {
|
||||
return Object.keys(m.components).map(key => {
|
||||
return m.components[key]
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
resolve (
|
||||
to: RawLocation,
|
||||
current?: Route,
|
||||
append?: boolean
|
||||
): {
|
||||
location: Location,
|
||||
route: Route,
|
||||
href: string,
|
||||
// for backwards compat
|
||||
normalizedTo: Location,
|
||||
resolved: Route
|
||||
} {
|
||||
const location = normalizeLocation(
|
||||
to,
|
||||
current || this.history.current,
|
||||
append,
|
||||
this
|
||||
)
|
||||
const route = this.match(location, current)
|
||||
const fullPath = route.redirectedFrom || route.fullPath
|
||||
const base = this.history.base
|
||||
const href = createHref(base, fullPath, this.mode)
|
||||
return {
|
||||
location,
|
||||
route,
|
||||
href,
|
||||
// for backwards compat
|
||||
normalizedTo: location,
|
||||
resolved: route
|
||||
}
|
||||
}
|
||||
|
||||
addRoutes (routes: Array<RouteConfig>) {
|
||||
this.matcher.addRoutes(routes)
|
||||
if (this.history.current !== START) {
|
||||
this.history.transitionTo(this.history.getCurrentLocation())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function registerHook (list: Array<any>, fn: Function): Function {
|
||||
list.push(fn)
|
||||
return () => {
|
||||
const i = list.indexOf(fn)
|
||||
if (i > -1) list.splice(i, 1)
|
||||
}
|
||||
}
|
||||
|
||||
function createHref (base: string, fullPath: string, mode) {
|
||||
var path = mode === 'hash' ? '#' + fullPath : fullPath
|
||||
return base ? cleanPath(base + '/' + path) : path
|
||||
}
|
||||
|
||||
VueRouter.install = install
|
||||
VueRouter.version = '__VERSION__'
|
||||
|
||||
if (inBrowser && window.Vue) {
|
||||
window.Vue.use(VueRouter)
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import View from './components/view'
|
||||
import Link from './components/link'
|
||||
|
||||
export let _Vue
|
||||
|
||||
export function install (Vue) {
|
||||
if (install.installed && _Vue === Vue) return
|
||||
install.installed = true
|
||||
|
||||
_Vue = Vue
|
||||
|
||||
const isDef = v => v !== undefined
|
||||
|
||||
const registerInstance = (vm, callVal) => {
|
||||
let i = vm.$options._parentVnode
|
||||
if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
|
||||
i(vm, callVal)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
||||
Object.defineProperty(Vue.prototype, '$router', {
|
||||
get () { return this._routerRoot._router }
|
||||
})
|
||||
|
||||
Object.defineProperty(Vue.prototype, '$route', {
|
||||
get () { return this._routerRoot._route }
|
||||
})
|
||||
|
||||
Vue.component('RouterView', View)
|
||||
Vue.component('RouterLink', Link)
|
||||
|
||||
const strats = Vue.config.optionMergeStrategies
|
||||
// use the same hook merging strategy for route hooks
|
||||
strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created
|
||||
}
|
||||
Reference in New Issue
Block a user