第一步,下载插件
npm install markdown-it
第二步,使用插件渲染
<template><div v-html="htmlContent"></div>
</template><script setup>
import { ref, computed } from 'vue';
import MarkdownIt from 'markdown-it';
// 创建 MarkdownIt 实例
const md = new MarkdownIt();
// 定义一个响应式的 Markdown 文本
const markdownText = ref('# Hello, World!\nThis is a markdown paragraph in script setup.');
// 通过计算属性将 Markdown 文本转换为 HTML 内容
const htmlContent = computed(() => md.render(markdownText.value));
</script>
实际页面的应用:
<script setup>
import { inject, onMounted, ref, computed, watch } from 'vue';
import MarkdownIt from 'markdown-it';
const axios = inject('$axios');
const view = ref([]);
const getPostArticleView = async () => {const res = await axios({method: 'post',url: '/articles/view/1',});view.value = res.data.data;console.log(view);
};let hasExecuted = false;onMounted(() => {if (!hasExecuted) {getPostArticleView();hasExecuted = true;}
});const md = new MarkdownIt();
// 用于存储转换后的HTML内容,初始为空
const htmlContent = ref('');
watch(view, (newView) => {if (newView && newView.body && newView.body.content) {// 当view有有效数据时,进行Markdown转换htmlContent.value = md.render(newView.body.content);}
}, { immediate: false });
</script><template><div id="article"><div class="textSpring"><h1>{{view.title}}</h1><hr><div v-html="htmlContent"></div></div></div>
</template><style scoped>#article{padding: 20px;}.textSpring{margin: 0 auto;border: 1px solid black;border-radius: 5px;width: 60%;}
</style>
文章封面: