-
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathlink.js
102 lines (93 loc) · 2.69 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
/* @flow */
import { createRoute, isSameRoute, isIncludedRoute } from '../util/route'
import { _Vue } from '../install'
// 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 { normalizedTo, resolved, href } = router.resolve(this.to, current, this.append)
const classes = {}
const activeClass = this.activeClass || router.options.linkActiveClass || 'router-link-active'
const compareTarget = normalizedTo.path ? createRoute(null, normalizedTo) : 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
// don't redirect if `target="_blank"`
/* istanbul ignore if */
const target = e.target.getAttribute('target')
if (/\b_blank\b/i.test(target)) return
e.preventDefault()
if (this.replace) {
router.replace(normalizedTo)
} else {
router.push(normalizedTo)
}
}
}
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) {
// in case the <a> is a static node
a.isStatic = false
const extend = _Vue.util.extend
const aData = a.data = extend({}, a.data)
aData.on = on
const aAttrs = a.data.attrs = extend({}, a.data.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
}
}
}
}