同样 我们还是去官方网看一下
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
嵌套的路由/视图表
模块化的、基于组件的路由配置
路由参数、查询、通配符
基于 Vue.js 过渡系统的视图过渡效果
细粒度的导航控制
带有自动激活的 CSS class 的链接
HTML5 历史模式或 hash 模式,在 IE9 中自动降级
自定义的滚动条行为
他的作用主要作用是让我们的前端变得更加模块化。
使用
我们需要在我们的项目中添加router 如果出现错 就按照他的提示进行修复
npm install vue-router --save-dev
在components文件夹下面 创建我们所需要的组建
我们这里创建了两个组建
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<!--scoped 是作用域的意思 加上他的意思style只对当前文件生效-->
<style scoped>
</style>
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
然后在我们的项目中创建一个 router文件夹用来单独存放router。
首先是我们是先导入我们所需要的模块,然后在是导入我们的组件,接着是声明路由使用,重要的我们配置路由的导出,我们创建一个VueRouter对象在这里面添加一个routes数组在数组里面配置路由相关的信息。
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
},
]
})
现在需要在main.js中添加,这里一般只需要添加一次,如果路由配置更改则需要跟换路径。
import Vue from 'vue'
import App from './App'
import router from './router/index'//扫描里面的路由
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
})
最后我们需要在App.vue中的template模板中引入我么路由连接和跳转之后的显示
<template>
<div id="app">
<h1>Vue-Router</h1>
<!-- 引入路由连接-->
<router-link to="/conten">首页</router-link>
<router-link to="/main">内容页</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>
大致路径
component->router->main.js->App.js