我使用vue 3
我有一个在其中加载组件的 View 。每次单击文本时,router.push
被调用,并加载一个带有一些参数的组件
click here
<h3 @click="handleClick('intro', 'abc')" >intro</h3>
to load component here
<router-view></router-view>
点击是这样处理的
setup(){
const router = useRouter();
const handleClick = (part, term)=>{
router.push({name:part, params: {term}}).catch(err => {});
}
return{handleClick}
}
所以router.push
加载于<router-view>
另一个较小的组件(名为 intro),根据应用程序的路由器,设置如下
path: '/book',
name: 'book',
component: book,
children:[
{
path: 'intro/:term',
name: 'intro',
component: Intro
},
]
该组件已加载到 View 内,并且 url 类似于 /book/intro/abc
在介绍组件内,处理路线的更改并向下滚动 abc
id,我愿意
const route = useRoute();
let id = false;
let mounted = ref(false);
//grab the term from route, to set it as id and if component is mounted, scroll to id
watchEffect(()=>{
id = route.params.term;
let el = document.getElementById(id);
if (mounted && el) {
el.scrollIntoView({behavior: "smooth"});
id = false;
}
})
//check if mounted and if also id that came from route exists, scroll to id
onMounted(() => {
mounted = true;
let el = document.getElementById(id);
if (id && el) {
el.scrollIntoView({behavior: "smooth"});
id = false;
}
})
问题 这是有效的,并且基于路由,加载组件并设置它将滚动到的 id。
但是,如果我滚动到一个 id,然后在页面中随机滚动,然后单击相同的 id 进行滚动,它不会再次滚动到该 id,因为 id 不会更改,因此路由不会触发另一个事件。
示例:网址为/book/intro/abc
。如果我随机滚动然后单击 abc
, url 相同,不会触发任何事件,不会再次滚动回 abc。
我该如何解决这个问题?我想避免在我的网址中出现主题标签、查询或问号。理想情况下,我想要“干净”的网址,例如 /book/part/term
我想在 View 内加载 url 指示的部分,而不是将所有部分作为超长文本加载到 View 内。
编辑我也想避免重新加载
谢谢
最佳答案
您可以观察整个路由对象并使用 force
强制更改路由器。选项。
/* In the template */
<router-link :to="{ path: 'some-path', force: true }">link</router-link>
// In the script
const route = useRoute()
watch(() => route, () => {
console.log('route changed')
}, {
deep: true
})
关于vue.js - 强制 vue 3 路由器两次到达同一条路线 - 将其识别为新事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72027066/