vuepress锚点hash滚动问题

2022-08-02,,

vuepress锚点hash滚动scroll问题

问题描述

vuepress建立网站的某个URL如果带有锚点,如http://test/test-hash.html#hasherror,刷新该URL,并不能滑动到相应的hasherror锚点,或者打开新的带有锚点的链接不能跳到相应的地方。

研究调查

  1. 在vuepress的github issue中找到相关的问题——Initial load does not scroll to the heading referenced by the document hash

  2. 又在1的问题下发现关于中文hash需要解码(decodeURIComponent)的提示——中文在URL中会被转码,需要使用decodeURIComponent方法解码

解决方案

根据以上调查以及实践,解决方案如下:


在.vuepress文件夹下添加enhanceApp.js文件

export default ({ router }) => {
	if(typeof process === 'undefined' || process.env.VUE_ENV !== 'server') {
		router.onReady(() => {
			const { app } = router;

			app.$once("hook:mounted", () => {
				setTimeout(() => {
					const { hash } = document.location;
                    if (hash.length > 1) {
            		const id = decodeURIComponent(hash.substring(1));
            		const element = document.getElementById(id);
            		if (element) element.scrollIntoView();
          }
				}, 500);
			});	
		});
	}
}

注意:如果hash有中文,要加decodeURIComponent

本文地址:https://blog.csdn.net/sendudu/article/details/107368962

《vuepress锚点hash滚动问题.doc》

下载本文的Word格式文档,以方便收藏与打印。