vue-router说明
Vue Router 是Vue.js官方的路由管理器。它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌。包含功能有:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于Vue.js过度系统的视图过度效果
- 细粒度的导航控制
- 带有自动激活的CSS class 的链接
- HTML5 历史模式或hash模式,在IE6中自动降级
- 自定义的滚动条行为
安装
vue-router是一个插件包,所以我们还是需要用 npm/cnpm进行安装。
npm install vue-router --save-dev
在一个模块化工程中使用它,必须通过 Vue.use(“路由名称”) 明确地安装路由功能
vue-router使用
1.在src文件夹下建立components组件文件夹,分别建立Comtent.vue和Main.vue两个组件
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<style scoped>
</style>
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
2.在src文件夹下建立router文件夹,在文件夹下建立 index.js用于路由页面的跳转配置
import Vue from 'vue'
import VueRouter from 'vue-router'
//导入自定义组件
import Content from '../components/Content'
import Main from '../components/Main'
//安装路由,显示引用
Vue.use(VueRouter);
//配置导出路由
export default new VueRouter({
routes:[
{
//路由路径
path:'/content',
//自定义路由名称
name:'content',
//路由跳转的组件
component:Content
},
{
//路由路径
path:'/main',
//自定义路由名称
name:'main',
//路由跳转的组件
component:Main
}
]
});
3.在main.js中引用自定义路由配置并开启
import Vue from 'vue'
import App from './App'
import router from './router'//导入自定义路由配置
new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
})
4.在App.vue中配置并测试路由,主要利用<router-link to="/路由配置中的path">XX</router-link>
<template>
<div id="app">
<router-link to="/main">首页</router-link>
<router-link to="/content">内容页</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
注意:<router-link> 和<router-view>两个标签缺一不可
目录结构如图:
测试结果如图: