简介:

vue-router官网 用 Vue.js + vue-router 可以快速创建SPA(单页应用程序),是非常简单的。使用 Vue.js ,我们已经可以通过组合Component来组成应用程序。 引入 vue-router 的过程:将组件(components)映射到路由(routes),然后告诉 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
// 注意顺序不能颠倒!!!
<script src="D:\Github\vue\lib\vue.js"></script>
<script src="D:\Github\vue\lib\vue-router.js"></script>
<script>
window.onload = function() {
// 1. 准备template
var A = Vue.extend({
template: "<h3>我是A</h3>"
})
var B = Vue.extend({
template: "<h3>我是B</h3>"
})
// 2. 准备routes
const routes = [{
path: "/A",
component: A,
}, {
path: "/B",
component: B,
}, {
path: '*',// 默认打开
redirect:'/A'
}]

// 3. 调用vue-router
const router = new VueRouter({
//这里等价于routes: routes,不要随意写其他的名字!!!
routes,
})
// 4. 挂载到vue上
new Vue({
router,
el: '#box'
})
}
</script>
</head>
<body>
<div id="box">
<div>
<router-link to="/A">A</router-link>
<router-link to="/B">B</router-link>
</div>
<div>
<router-view></router-view>
</div>

</div>
</body>
</html>


模块化使用方法

部分目录结构如下:

1
2
3
4
5
6
7
8
9
10
├──node——modules
├──src
├──assets
├──components // 用来存放组件A.vue和B.vue
│ ├──A.vue
│ └──B.vue
├──App.vue
├──main.js
├──router.config.js // router.config.js 用来存放路由信息
└──...

一、组件定义

A.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<h3>我是A</h3>
</template>

<script>
export default {

}
</script>

<style>

</style>

B.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<h3>我是B</h3>
</template>

<script>
export default {

}
</script>

<style>

</style>

二、路由信息 router.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import A from './components/A.vue'
import B from './components/B.vue'

export default {
routes: [{
path: "/A",
component: A,
}, {
path: "/B",
component: B,
}, {
path: "*",
redirect: '/A'
}]
}

三、调用router并挂载到vue上 main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Vue from 'vue'
import VueRouter from 'vue-router'

import App from './App.vue'
import routes from './router.config.js'

Vue.use(VueRouter);

const router = new VueRouter(routes)
new Vue({
el: '#app',
router,
render: h => h(App)
})

四、router-link与router-view App.vue

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
<template>
<div id="app">
{{msg}}
<ul>
<li>
<router-link to='/A'>A</router-link>
<router-link to='/B'>B</router-link>
</li>

</ul>
<div>
<router-view></router-view>
</div>
</div>
</template>

<script>
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>

<style>

</style>