笔记:路由页面间的跳转
- 背景
- 解决
- 三种情况
- 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,重新加载数据
//写法一 <script setup> import { useRoute } from "vue-router"; const route = useRoute(); watch(route, (to, from) => { //执行重新加载数据 }) </script> //写法二 <script> export default { watch: { $route: function (to, from) { }, }, }; </script>
复制
三种情况
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); };
复制