文章目录
一、什么是vue router
Vue Router 是 Vue.js (opens new window)官方的路由管理器。它和 Vue.js 的核心深度集成
,让构建单页面应用变得易如反掌。
包含的功能有:
-
嵌套的路由/视图表
-
模块化的、基于组件的路由配置
-
路由参数、查询、通配符
-
基于 Vue.js 过渡系统的视图过渡效果
-
细粒度的导航控制
-
带有自动激活的 CSS class 的链接
-
HTML5 历史模式或 hash 模式,在 IE9 中自动降级
-
自定义的滚动条行为
二、vue router的安装
Vue Router是一个插件包,我们要使用,我们需要同npm/cnpm进行安装
注意:
我们是基于vue-cli项目【点击查看】进行安装的
在的vue-cli项目【点击查看】下使用下面命令进行安装,或者直接使用IEDA的Terminal
命令:npm install vue-router --save-dev
可能会有问题,按照它给的提示进行修复
此时,在项目的node_modules目录
下面,我们已经有vue-router
三、vue router的使用
原理图
在vue中使用import VueRouter from 'vue-router'
将vue router导入。
如果在一个模块化工程中使用它,必须要通过 Vue.use() 明确地安装路由功能:
import Vue from 'vue'
import VueRouter from 'vue-router'
//显式的声明使用VueRounter
Vue.use(VueRouter)
下面,我来写一个简单的例子
第一步:依赖组件的搭建
首先,我们需要编写一个Main.vue
组件(主页)和一个Content.vue
组件(内容页)用于跳转的演示。
Main.vue
<template>
<h3>欢迎来到,寒江の首页</h3>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
Content.vue
<template>
<h3>欢迎来到,寒江の内容页</h3>
</template>
<script>
export default {
name: "content"
}
</script>
<style scoped>
</style>
App.vue
<template>
<div id="app">
<h2>欢迎来到,寒江のvue-router世界</h2>
<router-link to="/show/main">首页</router-link>
<router-link to="/show/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文件夹
,并在该文件夹下创建index.js(index.js其实就是router的配置文件,官方建议命名成index.js,第三步
的1
中会说明为什么)
1、路由的显式声明使用
我们要是index.js中使用vue-router,需要如下声明
import Vue from 'vue'
import VueRouter from 'vue-router'
//使用vue-router
Vue.use(VueRouter);
2、路由配置的容器
在index.js中的路由配置,我们需要写在如下的配置中
export default new VueRouter({
routes:[
{
path:'', //路由的路径
name: '', //路由名
component: ... //跳转到的组件
}
]
})
3、路由配置的具体实现
我们来配置跳转Main.vue的设置,我们用到了Main.vue,所以需要引入
import Main from "../components/Main";
编写路由配置
routes:[
{
path:'/main',
name: 'main',
component: Main
},
]
我们来配置跳转Content.vue的设置,我们用到了Content.vue,所以需要引入
import Content from "../components/Content";
编写路由配置
routes:[
{
path:'/content',
name: 'content',
component: Content
},
]
4、上述关于index.js的整合
import Vue from 'vue'
import VueRouter from 'vue-router'
import Content from "../components/Content";
import Main from "../components/Main";
//使用vue-router
Vue.use(VueRouter);
//配置导出路由
export default new VueRouter({
routes:[
{
//路由的路径
path:'/content',
name: 'content',
//跳转的组件
component: Content
},
{
//路由的路径
path:'/main',
name: 'main',
//跳转的组件
component: Main
}
]
})
第三步:在App.vue中使用路由
1、在main.js中导入路由
因为main.js是与App.vue向绑定的,如果我们要是在App.vue中#app
使用index.js配置好的路由,那么我们需要将index.js引入main.js。
import router from './router' //自动的扫描router下的index
这也是为什么官方推荐我们使用index.js作为路由配置名的原因。
现在我们在main.js中引入了index.js,但是需要配置路由,方法很简单,如下:
2、在App.vue中实现vue-router
介绍两个新的标签
< router-link to=“路由路径”>:其作业就相当于是html中的< a>标签
< router-view>:当点击< router-link to=“路由路径”>时,相关组件的内容将会显示在< router-view>所在的位置,起到定位显示组件。
<template>
<div id="app">
<h2>欢迎来到,寒江のvue-router世界</h2>
<router-link to="/main">首页</router-link>
<router-link to="/content">内容页</router-link>
<router-view></router-view>
</div>
</template>
运行命令: npm run dev
我们可以发现,并没有默认显示页
3、设置< router-view>的默认显示组件
我只需要在index.js中的routes
中加上如下代码即可
{
//默认路径
path:'/',
name: 'main',
component: Main
},
这里有一个下细节需要注意一下,如果将内容写在 < div id="app">的外面
,那么…
四、路由嵌套
实际生活中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件,例如:
由上图,我们可知,路由嵌套的应用在开发中最长见的就是在显示页面与导航栏的关系了。
1、语法
路由嵌套的语法很简单,如下:
children:其为路由嵌套的关键字,写在路由A的children属性中的路由,即为A的嵌套路由
。
const router = new VueRouter({
routes: [
{
path: '/user/:id',
component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}
]
}
]
})
注意事项:在children中的path的开始是没有
/的
,比如path:"/next/cont"是不对的,path:"next/cont"是对的。
2、实例
我们做一个小例子,将“三”中的例子改成路由嵌套的形式…
原本的Content组件和Main组件不需要改变…
我们需要新添加两个组件:一个是用于展示Content和Main组件的Show组件,另一个是“Error404组件”。
Show.vue
<template>
<div>
<h2>欢迎来到,寒江のvue-router世界</h2>
<router-link to="/show/main">首页</router-link>
<router-link to="/show/content">内容页</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "Show"
}
</script>
<style scoped>
</style>
Error.vue
<template>
<div>
<div class="main">
抱歉,你的页面走丢了!
</div>
请访问:<a href="http://localhost:8080/#/show">http://localhost:8080/#/show</a>
</div>
</template>
<script>
export default {
name: "Error"
}
</script>
<style scoped>
.main{
width: 500px;
height: 200px;
margin: 100px auto;
line-height: 200px;
align-content: center;
font-size: 25px;
}
</style>
我们还需要改动一下App.vue中的模版
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
对应的路由配置文件 index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Content from "../components/Content";
import Main from "../components/Main";
import Show from "../components/Show";
import Error from "../components/Error";
//使用vue-router
Vue.use(VueRouter);
//配置导出路由
export default new VueRouter({
mode: history,
routes:[
{
path:'/show',
name:'show',
component:Show,
children:[
{
path:'content/:author/:info',
name: 'content',
component: Content,
props: true
},
{
path:'main/:author/:info',
name: 'main',
component: Main,
props: true
}
]
},
{ //404路由配合
path:'*',
name: 'error',
component: Error
}
]
})
3、效果展示
4、原理图
这样我们的代码就弄完了,你是不是觉得有点懵逼,说实话,我在开始整理的时候是很懵逼的,感觉乱糟糟的,这个套哪个,哪个套这个… 不要代码我给大家花了一张图:
五、参数传递与重定向
到此,我们还没有进行传值操作,目前只是解决了页面(组件)的 跳转…,下面我们将解决参数传递与重定向。
1、参数传递
第一种方式:耦合性较高
:to:首先要先绑定route-link的参数to,to中的值是对象。
name:’’:值得注意的是,这里的name是指路由配置中的name
,而不是组件的name,将会将参数传递给对应的组件。
params:{}:其中写参数,通过键值对的形式书写。
<router-link :to="{name:'main', params:{author:'寒江', info:'首页'}}">首页</router-link>
<router-link :to="{name:'content',params: {author:'寒江', info:'内容页'}}">内容页</router-link>
/:参数名:这里的参数名要和上面的params中的参数名相同
。其作用是在url中显示专递的值,类似于get请求;也可不不写,那么就相当于post请求。
{
path:'/show',
name:'show',
component:Show,
children:[
{
path:'content/:author/:info',
name: 'content',
component: Content
},
{
path:'main/:author/:info',
name: 'main',
component: Main
}
]
},
{{$route.params.参数名}}:取出参数名对应的
参数值。
<template>
<h3>欢迎来到,{{$route.params.author}}の{{$route.params.info}}</h3>
</template>
第二种方式:一种相对解耦的形式(推荐)
props: true:其作用是声明通过route-link传递的参数是可以在相对应的组件中通过props属性进行接收,当然组件中的属性名要和参数名相同
{
path:'/show',
name:'show',
component:Show,
children:[
{
path:'content/:author/:info',
name: 'content',
component: Content,
props: true
},
{
path:'main/:author/:info',
name: 'main',
component: Main,
props: true
}
]
},
props:[‘author’,‘info’]:用于绑定接收传递过来的参数。
<template>
<h3>欢迎来到,{{author}}の{{info}}</h3>
</template>
<script>
export default {
name: "Main",
props:['author','info']
}
</script>
<template>
<h3>欢迎来到,{{author}}の{{info}}</h3>
</template>
<script>
export default {
name: "Content",
props:['author','info']
}
</script>
2、重定向
在vue中实现重定向不要太简单,重定向会导致地址栏(url)发生改变…
配置重定向(index.js:路由的配置文件)
当访问http://localhost:8080/#/geback时,会自定跳转到http://localhost:8080/#/show
{
path:'/goback',
redirect:'/show'
}
六、路由的模式与路由钩子
1、路由的模式
路由有两种模式
- hash(默认):
路径带 # 号
,例如:http://localhost/#/show - history:
路径不带 # 号
,例如:http://localhost/show
export default new VueRouter({
mode: history,
routes:[
...
]
})
2、路由钩子
安装:Axios
npm install --save axios vue-axios
将下面代码加入入口文件:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
介绍两个路由相关的钩子
进入路由之前的钩子…
beforeRouteEnter:(to, from, next)=>{
...
next(...);
}
进入路由之后的钩子…
beforeRouteLeave:(to, from, next)=>{
...
next(...);
}
参数解释:
to:路由将要跳转的路径信息
from:路由跳转前的路径信息
next:路由的控制参数
next() :跳到下一个页面
next(’/path’) :路由的跳转方向,使其跳转到另一个路由
next(false) :返回原来页面
next((vm)=>{}) : 仅在beforeRouteEnter中使用,vm是组件实例
下面举一个例子,在进入路由之前,获取data.json文件中的数据
第一步:创建一个Data.vue组件
1.在data()中编写一个与json字符串格式相同的对象info
data(){
return{
//格式要和json一致
info:{
title:null,
url:null,
classify:{
name01:null,
name02:null,
name03:null,
name04:null
},
links:[
{
title:null,
url:null
},
{
title:null,
url:null
},
{
title:null,
url:null
},
{
title:null,
url:null
}
]
}
}
}
2.利用Axios编写一个getData方法,或者json文件
this.info=res.data:将获取到的数据res赋值给data()中的info,因为info与与json字符串格式相同,所以可以直接赋值
methods:{
getData:function () {
this.axios.get('../../static/json/data.json').then((res)=>{
console.log(res)
this.info=res.data
}).catch((error)=>{
console.log(error)
})
}
},
3.编写beforeRouteEnter和beforeRouteLeave方法
beforeRouteEnter:(to, from, next) => {
console.log("进入路由之前...")
next((vm)=>{
vm.getData()
})
},
beforeRouteLeave:(to, from, next) => {
console.log("进入路由之后...")
next()
},
4.编写模板
<template>
<div>
<h2>{{info.title}}:<a :href=info.url>{{info.url}}</a></h2>
<div>
<h3 v-for="item in info.links">
{{item.title}}:<a :href=item.url>{{item.url}}</a>
</h3>
</div>
</div>
</template>
整合
<template>
<div>
<h2>{{info.title}}:<a :href=info.url>{{info.url}}</a></h2>
<div>
<h3 v-for="item in info.links">
{{item.title}}:<a :href=item.url>{{item.url}}</a>
</h3>
</div>
</div>
</template>
<script>
export default {
name: "Data.vue",
methods:{
getData:function () {
this.axios.get('../../static/json/data.json').then((res)=>{
console.log(res)
this.info=res.data
}).catch((error)=>{
console.log(error)
})
}
},
beforeRouteEnter:(to, from, next) => {
console.log("进入路由之前...")
next((vm)=>{
vm.getData()
})
},
beforeRouteLeave:(to, from, next) => {
console.log("进入路由之后...")
next()
},
data(){
return{
//格式要和json一致
info:{
title:null,
url:null,
classify:{
name01:null,
name02:null,
name03:null,
name04:null
},
links:[
{
title:null,
url:null
},
{
title:null,
url:null
},
{
title:null,
url:null
},
{
title:null,
url:null
}
]
}
}
}
}
</script>
<style scoped>
</style>
第二步:创建相关路由信息
我们依然将Data.vue的路由作为Show.vue的子路由(index.js)
{
path:'data',
name:'data',
component:Data
}
第三步:更新Show.vue的组件
添加一个route-link
<router-link to="/show/data">数据页</router-link>
点击“数据页”之后的效果
点击“返回”之后的效果
vue-router文档:https://router.vuejs.org/zh/installation.html/
axios文档:http://www.axios-js.com/zh-cn/docs/vue-axios.html
你爱我,我会陪你;你不爱我,我给你自由。这就是傻傻的我,那个在乎你的我…