Skip to content

vite vue3 预览模式使用自定义锚点不能正常跳转到相应标题 #311

@X-WC

Description

@X-WC

代码如下

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const text = ref( `
# heading 1
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent

## heading 2
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent

### heading 3
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent

## heading 2
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent

### heading 3
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent
contentcontentcontent
`);

const preview = ref();
const titles = ref([]);

onMounted(() => {
	const anchors = preview.value.$el.querySelectorAll('h1,h2,h3,h4,h5,h6');
	const titlesList = Array.from(anchors).filter((title) => !!title.innerText.trim());

	if (!titlesList.length) {
		titles.value = [];
		return;
	}

	const hTags = Array.from(new Set(titlesList.map((title) => title.tagName))).sort();

	titles.value = titlesList.map((el) => ({
		title: el.innerText,
		lineIndex: el.getAttribute('data-v-md-line'),
		indent: hTags.indexOf(el.tagName),
	}));
});

const handleAnchorClick = (anchor) => {
	const { lineIndex } = anchor;

	const heading = preview.value.$el.querySelector(`[data-v-md-line="${lineIndex}"]`);

	if (heading) {
		// 注意:如果你使用的是编辑组件的预览模式,则这里的方法名改为 previewScrollToTarget
		preview.value.previewScrollToTarget({
			target: heading,
			scrollContainer: window,
			top: 60,
		});
	}
};
</script>

<template>
	<div>
		<div v-for="anchor in titles" :style="{ padding: `10px 0 10px ${anchor.indent * 20}px` }" @click="handleAnchorClick(anchor)">
			<a style="cursor: pointer">{{ anchor.title }}</a>
		</div>
		<v-md-editor ref="preview" default-show-toc mode="preview" v-model="text" height="600px"></v-md-editor>
	</div>
</template>

<style scoped lang="scss">
</style>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions