vue3 项目构建-8-展示 markdown 文档

第一步,下载插件

复制代码
npm install markdown-it

第二步,使用插件渲染

javascript 复制代码
<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>

实际页面的应用:

javascript 复制代码
<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>

文章封面:

相关推荐
db_lnn_202124 分钟前
【vue】全局组件及组件模块抽离
前端·javascript·vue.js
Qin_jiangshan34 分钟前
vue实现进度条带指针
前端·javascript·vue.js
天高任鸟飞dyz35 分钟前
tabs切换#
javascript·vue.js·elementui
菜鸟una41 分钟前
【layout组件 与 路由镶嵌】vue3 后台管理系统
前端·vue.js·elementui·typescript
小张快跑。42 分钟前
【Vue3】使用vite创建Vue3工程、Vue3基本语法讲解
前端·前端框架·vue3·vite
Zhen (Evan) Wang1 小时前
.NET 8 API 实现websocket,并在前端angular实现调用
前端·websocket·.net
星空寻流年1 小时前
css3响应式布局
前端·css·css3
Anesthesia丶1 小时前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
Rverdoser2 小时前
代理服务器运行速度慢是什么原因
开发语言·前端·php
航Hang*2 小时前
前端项目2-01:个人简介页面
前端·经验分享·html·css3·html5·webstorm