forked from vuejs/vue-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlink.js
104 lines (95 loc) · 2.74 KB
/
link.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* @flow */
import { cleanPath } from '../util/path'
import { createRoute, isSameRoute, isIncludedRoute } from '../util/route'
import { normalizeLocation } from '../util/location'
// work around weird flow bug
const toTypes: Array<Function> = [String, Object]
export default {
name: 'router-link',
props: {
to: {
type: toTypes,
required: true
},
tag: {
type: String,
default: 'a'
},
exact: Boolean,
append: Boolean,
replace: Boolean,
activeClass: String
},
render (h: Function) {
const router = this.$router
const current = this.$route
const to = normalizeLocation(this.to, current, this.append)
const resolved = router.match(to, current)
const fullPath = resolved.redirectedFrom || resolved.fullPath
const base = router.history.base
const href = createHref(base, fullPath, router.mode)
const classes = {}
const activeClass = this.activeClass || router.options.linkActiveClass || 'router-link-active'
const compareTarget = to.path ? createRoute(null, to) : resolved
classes[activeClass] = this.exact
? isSameRoute(current, compareTarget)
: isIncludedRoute(current, compareTarget)
const on = {
click: (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
e.preventDefault()
if (this.replace) {
router.replace(to)
} else {
router.push(to)
}
}
}
const data: any = {
class: classes
}
if (this.tag === 'a') {
data.on = on
data.attrs = { href }
} else {
// find the first <a> child and apply listener and href
const a = findAnchor(this.$slots.default)
if (a) {
const aData = a.data || (a.data = {})
aData.on = on
const aAttrs = aData.attrs || (aData.attrs = {})
aAttrs.href = href
} else {
// doesn't have <a> child, apply listener to self
data.on = on
}
}
return h(this.tag, data, this.$slots.default)
}
}
function findAnchor (children) {
if (children) {
let child
for (let i = 0; i < children.length; i++) {
child = children[i]
if (child.tag === 'a') {
return child
}
if (child.children && (child = findAnchor(child.children))) {
return child
}
}
}
}
function createHref (base, fullPath, mode) {
var path = mode === 'hash' ? '/#' + fullPath : fullPath
return base ? cleanPath(base + path) : path
}