vue通过router地址传参跳转同一路由页面,页面不刷新的解决办法
•
前端
笔记:路由页面间的跳转
- 背景
- 解决
- 三种情况
-
- 1、不同路由的跳转(/a/b1 => /a/b2)
- 2、相同路由不同参数间的跳转(/a/b?c=1 => /a/b?c=2)
- 3、相同页面锚点跳转(/a/b#id1 =>/a/b#id2)
背景
vue、 vue-router@4
记录一下最近遇到的vue路由页面间的跳转的问题,其中就涉及到了不同路由的跳转(/a/b1 => /a/b2)、相同路由不同参数间的跳转(/a/b?c=1 => /a/b?c=2)、相同页面锚点跳转(/a/b#id1 =>/a/b#id2)
解决
原因:渲染的是同一组件
解决:可以在不刷新的页面通过监听route,重新加载数据
//写法一
import { useRoute } from "vue-router";
const route = useRoute();
watch(route, (to, from) => {
//执行重新加载数据
})
//写法二
export default {
watch: {
$route: function (to, from) {
},
},
};
三种情况
1、不同路由的跳转(/a/b1 => /a/b2)
例子:
export default [
{
path: "/a/b1",
name: "b1",
component: () => import("@/pages/a/b.vue"),
},
{
path: "/a/b2",
name: "b2",
component: () => import("@/pages/a/b.vue"),
}
]
// b.vue
watch(route, (to, from) => {
//执行重新加载数据
})
2、相同路由不同参数间的跳转(/a/b?c=1 => /a/b?c=2)
解决方案同上
3、相同页面锚点跳转(/a/b#id1 =>/a/b#id2)
可以手动实现
export const onToAnchor = (id) => {
let timer = setTimeout(() => {
//未获取到id,不执行
if (!id) {
clearTimeout(timer);
timer = null;
return;
}
let element = document.querySelector(id);
if (element) {
element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest",
});
}
}, 0);
};
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/b4531bc3f4.html
