想必来查看笔者的这篇Vue Router文章的人,应该了解什么是Vue Router,至少知道其的作用是路由映射,所以笔者在这里不再赘述。
假设我们现在有一些简单的vue组件,
MyHeader.vue:
<template>
<div class="container">
this is header of each page
</div>
</template>
<script>
export default {
name: "my-header"
}
</script>
index.vue:
<template>
<div>
<div class="container">this is home page</div>
</div>
</template>
<script>
export default {
name: "index"
}
</script>
second.vue:
<template>
<div>
<div class="container">this is second page</div>
<span>{
{
id}}</span>
</div>
</template>
<script>
export default {
name: "second"
}
</script>
这三个组件中的container样式一样:
<style lang="scss" scoped>
.container{
border: #bfbfbf 1px solid;
width: 200px;
height: 100px;
margin:10px 0;
}
</style>
1. 构建基本的router
我们希望我们的单页面由my-header和一个index / second组件组成,页面中展示 index / second 需要使用router来解决。
router.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import index from "../view/index"
import second from "../view/second"
Vue.use(VueRouter)
const routes = [
{
path: '/',
redirect: '/home'
},
{
path:'/home',
name: 'home',
component: index,
},{
path:'/second',
name: 'second',
component: second,
}
]
let router = new VueRouter({
mode: 'history',
routes
}
export default router
这就是一个简单的router,当我们导航到指定路径时,<router-view/> 标签就会被相应的component组件替换。
我们这里在router.js直接引入了组件,为了提高带宽利用率,提高性能,我们使用动态引入的方式来加载模块:
//import second from "../view/second"
//component: second
component: () => import('../view/second')
注意:如果使用了异步加载组件的方式,我们需要使用@babel对此语法进行解析:
npm install --save-dev @babel/plugin-syntax-dynamic-import
修改babel配置:
{
"plugins": ["@babel/plugin-syntax-dynamic-import"]
}
为了方便路由切换,我们在my-header组件中增加两个router-link:
<template>
<div class="con