1. 安装 vue-router:
npm install vue-router --save
2. 新建router文件夹,在该文件夹下建 index.js 文件,引入并使用 vue-router:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
3. 在入口 js 文件中配置路由器:
完整代码如下:
import Vue from 'vue'
import App from './App.vue'
import router from './router/index' //配置路由器
new Vue({
el: '#app',
components:{
App
},
template:'<App/>',
router//配置对象的属性名称都是一些确定的名称,不能随便修改
})
4. 在 index.js 文件 中配置路由:
例如:
export default new VueRouter ({
// 注册应用中所有的路由
routes: [
{
path: '/about',
component: About
},
{
path: '/home',
component: Home,
},
{
path: '/',
redirect: '/about'
}
]
})
5. 路由链接,例:
<div class="list-group">
<!--生成路由链接-->
<router-link to="/about" class="list-group-item">About</router-link>
<router-link to="/home" class="list-group-item">Home</router-link>
</div>
6. 显示当前组件:
<router-view></router-view>
7. 缓存路由组件:
默认情况下,在切换路由时,路由对应的组件会被重新创建或销毁,每次切换的路由都是新创建的,如果可以缓存路由组件,可以提高用户体验,代码如下:
<keep-alive>
<router-view></router-view>
</keep-alive>
8. 嵌套路由:
例如:
{
path: '/home',
component: Home,
children: [
{
path: '/home/news',
component: News
},
{
path: 'message',
component: Message,
}
]
}
下面是个基本路由的示例:
main.js 文件:
import Vue from 'vue'
import App from './App.vue'
import router from './router/index' //配置路由器
new Vue({
el: '#app',
components:{
App
},
template:'<App/>',
router//配置对象的属性名称都是一些确定的名称,不能随便修改
})
App.vue 文件:
<template>
<div>
<div class="row">
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header"><h2>Router Test</h2></div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<!--生成路由链接-->
<router-link to="/about" class="list-group-item">About</router-link>
<router-link to="/home" class="list-group-item">Home</router-link>
</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<!--显示当前组件-->
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
Home.js 文件:
<template>
<div>
<h2>Home</h2>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
About.js 文件:
<template>
<div>
<h2>About</h2>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
效果如下所示: