VueRouter实现

VueRouter实现

我们知道,路由控制有两种方式: hashURL和HTML5的historyAPI.(这部分看文档mdn就成)

我们当前的实现使用的是hash路由

挑战1: 使用vue对router功能基本实现

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
<template>
<div id="app">
<!-- render main view here -->
<a href="#bar" v-if = "display == '#foo'">foo</a>
<a href="#foo" v-if = "display == '#bar'">bar</a>
</div>
</template>
<script>
window.addEventListener('hashchange', () => {
// Implement this!
let router = location.hash
app.changeRouter(router)
})

const app = new Vue({
el: '#app',
// Implement this!
data() {
return {
display: '#foo'
}
},
methods: {
changeRouter (router) {
this.display = router
}
},
})
</script>

在大多数spa页面中,每一个页面就是一个组件,这就是为什么组件的语法是is

1
<component :is='url'></component>

挑战2: 使用标签,在url进行转换的时候, 渲染不同的组件

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
<template>
<div id="app">
<!-- render main view here -->
<componet :is = 'display'></componet>
</div>
</template>
<script>
window.addEventListener('hashchange', () => {
// Implement this!
let router = location.hash
app.changeRouter(router)
})

const app = new Vue({
el: '#app',
// Implement this!
components: {
foo: {template: `<div>foo</div>`},
bar: {template: `<div>bar</div>`}
},
data() {
return {
display: 'foo'
}
},
methods: {
changeRouter (router) {
this.display = router
}
},
})
</script>

挑战3: 使用制作路由表(挖个坑, 这里要重新用render函数实现一次)

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
<template>
<div id="app">
<!-- render main view here -->
<a href="#foo">foo</a>
<a href="#bar">bar</a>
<component :is="routerType"></component>
</div>
</template>
<script>
const Foo = { template: `<div>foo</div>` }
const Bar = { template: `<div>bar</div>` }
const NotFound = { template: `<div>not found!</div>` }

const routeTable = {
// Implement this!
foo: "Foo",
bar: "Bar"
}

window.addEventListener('hashchange', () => {
// Implement this!
app.url = location.hash.slice(1)
})

const app = new Vue({
el: '#app',
// Implement this!,
components: {
Foo,
Bar,
NotFound
},
data() {
return {
url: location.hash.slice(1)
}
},
computed: {
routerType () {
return routeTable.hasOwnProperty(this.url) ? routeTable[this.url] : "NotFound"
}
}
})
</script>

正则路由与动态路由

动态路由: 动态路由指的是路由中包含变量。

例如: /user/:username

这里的:username就是一个变量, 指的是我们在router 中放入的string,例如: /user/paserdark

想象一下,动态路由和静态路由之间的区别是什么?就是url不一样,仅此而已。相比与之前的静态路由,动态路由的url包含了更多信息而已。我们要做的只是从url拿出信息,然后就是遵循静态路由的操作步骤。

对url的处理, 在node.js中, 有个工具模块就是专门处理query字符串的。功能是解析url, 拿出url中的信息。

解析url的库:path-to-regexp

使用方法:

  1. 先定义url的基本模式

  2. 处理输入url

  3. 获取格式化对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const pathToRegexp = require('./path-to-regexp')


    const path = '/bar/123'

    const keys = []

    const regx = pathToRegexp('/:type/:id?', keys)

    const result = regx.exec(path)// ['/bar/123', 'bar', '123'....]

挑战: 编写动态路由解析

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
<template>
<div id="app"></div>
</template>
<script>
const Foo = {
props: ['id'],
template: `<div>foo with id: {{ id }}</div>`
}
const Bar = { template: `<div>bar</div>` }
const NotFound = { template: `<div>not found!</div>` }

const routeTable = {
'/foo/:id': Foo,
'/bar': Bar
}

// pre-compile patterns into regex
// 编译路由表
const compiledRouteTable = {}
// 遍历routerTable, 提取router, 制作routerMap,
// 1. 这个map包含regex解析url方法(因为每个url的解析reg都不一样)
// 2. 包含router对应组件
// 3. dynamicSegments,承载keys,该keys为路由动态部分的信息,
// 如该例子为id, 我们在后面遍历这个keys拿到动态参数: {id: '123'}
Object.keys(routeTable).forEach(pattern => {
const dynamicSegments = []
compiledRouteTable[pattern] = {
component: routeTable[pattern],
regex: pathToRegexp(pattern, dynamicSegments),
dynamicSegments
}
})

// '#/foo/123' -> foo with id: 123
// '#/bar' -> Bar
// '#/404' -> NotFound

window.addEventListener('hashchange', () => {
app.url = window.location.hash.slice(1)
})

// path-to-regexp usage:
// const regex = pathToRegexp(pattern)
// const match = regex.exec(path)
// const params = regex.keys.reduce((params, key, index) => {
// params[key] = match[index + 1]
// }, {})

const app = new Vue({
el: '#app',
data: {
url: window.location.hash.slice(1)
},
render (h) {
const path = '/' + this.url

let componentToRender
let props = {}

// iterate through our compiled route table
// and check if a route matches the current path
// if it matches, extract dynamic segments (params) and use it as props
// for the matched component
Object.keys(compiledRouteTable).some(pattern => { // 为什么使用some,只匹配其中一条路由即可
const { component, regex, dynamicSegments } = compiledRouteTable[pattern]
const match = regex.exec(path)

if (match) {
// we have a match!
componentToRender = component
dynamicSegments.forEach(({ name }, index) => {
props[name] = match[index + 1]
})
return true
}
})

return h('div', { attrs: { id: 'app'} }, [
h(componentToRender || NotFound, {
props
}),
h('a', { attrs: { href: '#foo/123' }}, 'foo/123'),
' | ',
h('a', { attrs: { href: '#bar' }}, 'bar')
])
}
})
</script>