路由
路由是基于hash 和 history 封装的
- hash
// 例子
location.hash = 'demo'
- history
//例子
history.pushState(null,'title','test')
history.back()
history.forward()
history.go(3)
路由在vue中使用流程
ps. 如果在vue create my-project的时候没有选择路由,就手动安装一下。 详细见 router 网站
npm install vue-router
router 基础使用分为以下步骤
1. 在和main.js同级创建router文件夹,一般都是src下同级 下图
image.png
2. 在router文件下新建index.js文件
- 这个是router自动指定的目录,最好不要更改
- 在main.js引入的时候直接 '@/router' 即可
路由基础使用步骤
- 在router/index.js文件中导入router相关包。并且用Vue.use注册一下
import Vue from 'vue';
import VueRouter from 'vue-router';
//使用router插件
Vue.use(VueRouter);
- 声明使用VueRouter,添加一些相关配置,并且注册相关的组件。
const routes = [
{
path : '',
redirect : "/home"
},
{
path: '/home',
component: () => import('../views/Home')
},
{
path: '/about',
component: () => import('../views/About')
}
];
const router = new VueRouter({
mode : 'history', //使用history模式
base: process.env.BASE_URL,
routes
});
- 3.将声明的VueRouter导出
export default router
- 在入口main.js文件中导入router/index.js文件。 并且在Vue里注册
ps: 因为vue-router底层默认引用的就是router/index.js文件,所以可以简写直接导入到router/目录即可。
- 在入口main.js文件中导入router/index.js文件。 并且在Vue里注册
import router from "@/router";
new Vue({
router,
render: h => h(App)
}).$mount('#app')
- 上面的就是基础配置,配置好了就可以使用了。to是对应执行的路径。
<div class="centerText">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<router-link to="/user">用户</router-link>
</div>
<router-view />
router 一些常用字段
- to 对应路径。
- tag 设置类型。例如: tag="button",就是button样式
router路径定义传参字段
// 可以通过:userId 即可
{
path: '/user/:userId/:age',
name: 'User',
component: () => import("../views/User.vue")
}
v-bind:to使用,语法糖 :to
//通过name 进行传参
<router-link :to="{name: 'User',params: {userId: 'xiaofang',age: 20}}">用户</router-link>
this.$router常用字段
- this.$router.push
描述:跳转到不同的url,但这个方法回向history栈添加一个记录,点击后退会返回到上一个页面。
//跳转路径, 等同于 history.pushState()
this.$router.push('home');
//跳转路径
this.$router.push({path: '/about'});
// 跳转路径,传参数
this.$router.push({name: 'User',params: {userId: "123",age: 20}});
- this.$router.replace()
描述:同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。
//替换路径, 等同于history.replaceState
this.$router.replace('home');
- this.$router.go(n)
相对于当前页面向前或向后跳转多少个页面,类似 window.history.go(n)。n可为正数可为负数。正数返回上一个页面
//返回上一页, 相当于history.back()
this.$router.go(-1);
// 前进一步,等同于history.forward
this.$router.go(1);
// 前进3步
this.$router.go(3);
// 如果history不够用,就默认失败吧
this.$router.go(-100);
this.$router.go(100);
router接收路由参数的方法,分 ? 和 : 两种接收方式
this.$route是路由信息对象
- ? 形式的参数使用this.$route.query接收参数,结果是一个对象。
接收格式为?userId=123&age=20
//1.定义方式。只定义路径即可。
{
path: '/about',
name: 'About',
component: () => import('../views/About')
}
//2. 传参方式
<router-link :to="{name: 'User',query: {userId: userId,age}}">关于</router-link>
//3. 接收方式
- : 形式的参数使用this.$route.params接收参数,结果也是一个对象。
例如传参: :to({name: 'User',params: {userId: "123",age: 20}});
接收格式为 /user/123/20
//1.定义方式
{
path: '/user/:userId/:age',
name: 'User',
component: () => import("../views/User.vue")
}
//2.传参方式
<router-link :to="{name: 'User',params: {userId: userId,age}}">用户</router-link>
//3.接收方式
<p>接收参数 userId:{{this.$route.params.userId}} age:{{$route.params.age}}</p>
路由嵌套
开发中肯定会遇到路由嵌套的问题,路由嵌套进一层精简了代码,提高了组件的复用性,降低了代码的耦合度。
- 在路由中定义子路由使用children[]来包含多个路由,这里要注意的是path不需要添加 / 了
{
path: '/home',
name: 'Home',
children : [
{
path: '',
// name: 'News',
component : () => import('../components/News')
},
{
path: 'news',
name: 'News',
component : () => import('../components/News')
},
{
path: 'message',
name: 'Message',
component : () => import('../components/Message')
}
],
component: () => import('../views/Home')
}
- 使用路由嵌套同路由的正常使用一样。要在对应的路由.vue下使用,例如我上面定义的是在Home下的路由,那么路由应该写在Home.vue中
<p>当前为Home.vue页面</p>
<div>
<router-link :to="{name: 'News'}" tag="button">新闻</router-link>
<router-link :to="{name: 'Message'}" tag="button">消息</router-link>
</div>
<router-view />
Vue 导航守卫
提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。
通俗讲,导航守卫就是控制路由跳转前,或离开路由后的监听操作
更多路由导航守卫使用介绍访问 官网
- 组件内守卫,也就是在组件内才会执行。
beforeRouteEnter 守卫进入组件前调用
beforeRouteUpdate 路由改变时调用
beforeRouteLeave 离开该组件时候调用
<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
import News from "@/components/News";
import Message from "@/components/Message";
export default {
name: 'Home',
data(){
return {
togglePath : null
}
}
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
console.log("执行home的b beforeRouteEnter 因为当守卫执行前,组件实例还没被创建");
next()
},
beforeRouteUpdate(to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
console.log("执行home的b beforeRouteUpdate 因此组件实例会被复用。而这个钩子就会在这个情况下被调用。");
next()
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
this.togglePath = this.$route.path
console.log("执行home的b beforeRouteLeave 导航离开该组件的对应路由时调用。"+to.path+"\t"+from.path+"\t"+this.$route.path);
next()
},
}
</script>
keep-alive
keep-alive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染。 不会进入离开每次都执行创建和销毁。
更多动态组件 & 异步组件使用见 官网
- 基础使用
<keep-alive>
<component>
<!-- 该组件将被缓存! -->
</component>
</keep-alive>
- 过滤路径
<keep-alive include="abc">
<component>
<!-- name 为 abc 的组件将被缓存! -->
</component>
</keep-alive>
<keep-alive exclude="demo">
<component>
<!-- 除了 name 为 demo 的组件都将被缓存! -->
</component>
</keep-alive>
- 如果想某个路径网址被缓存,在router 里 增加 meta 属性。其中keepAlive为true表示缓存。
const routes = [
{
path: '/about',
name: 'About',
meta: {
keepAlive: true //about路径 需要缓存
},
component: () => import('../views/About')
},
{
path: '/user/:userId/:age',
name: 'User',
meta: {
keepAlive: false //user路径 不需要缓存
},
component: () => import("../views/User.vue")
}
];
- 需求:
默认显示 A
B 跳到 A,A 不刷新
C 跳到 A,A 刷新
实现方式
//在 A 路由里面设置 meta 属性:
{
path: '/',
name: 'A',
component: A,
meta: {
keepAlive: true // 需要被缓存
}
}
//在 B 组件里面设置 beforeRouteLeave:
export default {
data() {
return {};
},
methods: {},
beforeRouteLeave(to, from, next) {
// 设置下一个路由的 meta
to.meta.keepAlive = true; // 让 A 缓存,即不刷新
next();
}
};
//在 C 组件里面设置 beforeRouteLeave:
export default {
data() {
return {};
},
methods: {},
beforeRouteLeave(to, from, next) {
// 设置下一个路由的 meta
to.meta.keepAlive = false; // 让 A 不缓存,即刷新
next();
}
};