Vue2基础全套教程合集:点击跳转 Vue2高级全套教程合集:点击跳转
一、编程式路由导航
-
作用:不借助
<router-link>
实现路由跳转,让路由跳转更加灵活 -
使用场景:需要点击不是router-link标签定义的按钮进行跳转时,可以使用该方法。
-
具体编码:
//$router的两个API this.$router.push({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.replace({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.forward() //前进 this.$router.back() //后退 this.$router.go() //可前进也可后退
1. 编程式路由导航多次点击报错问题
- 原因:Vue-router@3.0 之后添加了同一路径跳转错误异常功能导致。
- 解决方法:重写
$router.push()
和$router.replace()
方法
// 重写push|replace
// function(跳转路径,请求成功回调函数,请求失败回调函数)
// call|apply区别
// 相同点:都可以调用函数一次,都可以篡改函数上下文一次。
// 不同点:call传参用逗号隔开,apply传参用数组传递。
VueRouter.prototype.push = function (location, resolve, reject) {
if (resolve && reject) {
//代表着两个形参接受参数【箭头函数】
originPush.call(this, location, resolve, reject);
} else {
originPush.call(this, location, () => {}, () => {});
}
};
VueRouter.prototype.replace = function (location, resolve, reject) {
if (resolve && reject) {
//代表着两个形参接受参数【箭头函数】
originReplace.call(this, location, resolve, reject);
} else {
originReplace.call(this, location, () => {}, () => {});
}
}
二、缓存路由组件
-
作用: 让不展示的路由组件保持挂载,不被销毁。
-
使用场景: 组件中含有输入框,在切换组件时不希望输入框内容清空,可以使用keep-alive缓存。
-
具体编码:
<keep-alive include="News"> <router-view></router-view> </keep-alive>
三、路由的激活与失活
- 作用: 路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
- 使用场景: 在组件中开启了定时器,可以在组件失活进行关闭,防止资源浪费。
- 具体名字:
activated
路由组件被激活时触发。deactivated
路由组件失活时触发。
<script> export default { name: 'News', data() { return { opacity: 1 } }, activated() { console.log('News组件被激活了') this.timer = setInterval(() => { console.log('@') this.opacity -= 0.01 if (this.opacity <= 0) this.opacity = 1 }, 16) }, deactivated() { console.log('News组件失活了') clearInterval(this.timer) }, } </script>