Vue-router路由转发
前言
为什么我们要学习vue-router路由转发呢?
由于VUE只专注于视图层,所以其他的都由一些组件来完成,路由转发就是其中一个,VUE Router是VUE官方的路由管理器,它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌。
包含以下功能:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于Vue.js过渡系统的视图过渡效果
- 细粒度的导航控制
- 带有自动激活的CSS class的链接
- HTML5历史模式或hash模式,在IE9中自动降级
- 自定义的滚动条行为
安装
我们基于vue-cli
进行测试学习,可以先查看node_modules中是否存在vue-router
使用如下命令进行安装:
npm install vue-router --save-dev
在当前项目下面进行安装
如果失败就使用cnpm
注意,最好不要用最新版本的,否则可能会出现问题,最好用3.x版本的。
如果你发现打包失败,或者提示找不到Router,就使用以下命令:
卸载原有路由:npm uninstall vue-router
安装3.0版本:npm i vue-router@3.5.2
vue2.x对应vue-router3.x
vue3.x对应vue-router4.x
使用
创建自己的组件
在src/componts
文件夹下面可以写我们自己的组件,这里我写了两个组件,一个是首页,一个是内容页面。
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
Content.vue
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<style scoped>
</style>
创建router文件夹
专门用来存放路由
我这里还创建了一个index.js
,这里的index不是首页的意思,而是主要配置文件的意思,把我们创建的组件配置进来。
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: [
{
//配置路由路径 相当于@RequestMapping
path: '/content',
name: 'content',
//跳转的组件
component: Content
},
{
//配置路由路径
path: '/main',
name: 'main',
//跳转的组件
component: Main
}
]
});
这里我创建了两个组件,一个首页,一个是内容页
并且导入到我的路由中去
import Content from '../components/Content'
import Main from '../components/Main'
配置路由
在main.js
文件中配置路由
import router from './router' //自动扫描里面的路由配置
//配置路由
router,
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router' //自动扫描里面的路由配置
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
})
使用路由
在App.vue
中使用路由
<template>
<div id="app">
<img src="./assets/logo.png">
<HelloWorld/>
<router-link to="/main">首页</router-link>
<router-link to="/content">内容页</router-link>
<router-view></router-view>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld'
export default {
name: 'App',
components: {
HelloWorld
}
}
</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 to="/main">首页</router-link>
<router-link to="content">内容页</router-link>
<router-view></router-view>
我们使用router-link
,类似于<a>
,to
来控制我们跳转的位置,类似于href
,然后使用<router-view>
来显示我们的视图。
这样配置以后,我们就可以专注于写我们自己的组件,然后把组件写入index.js,最后在App.vue中展示出来即可。
问题
执行npm run dev,报错,显示没有找到Router,但是我们在前面已经安装了Router,这是怎么回事呢?
解决:由于我们安装vue-router的时候,没有指定相应的版本,所以默认安装最新版本,我们的vue是2.x的,不能使用vue-router4.x的,语法不同,所以执行会报错,我们需要给vue-router降级。
卸载原有路由:npm uninstall vue-router
安装3.0版本:npm i vue-router@3.5.2
这样即可解决。