实现文章预览|青训营笔记

91 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 11 天

npx nuxi init nuxt-app

npm install

npm run dev

npm install --save-dev sass

这里写下自己负责的部分实现

文章预览

后台传html还是md?

  1. 后台数据传html。这样只需要预览html文本。这就想到v-md-editor中有html预览组件。( code-farmer-i.github.io/vue-markdow… )
  2. 后台数据传md。尝试使用mavon-editor ( github.com/hinesboy/ma… ) 回显,因为要使用window对象,而nuxt使用服务器渲染,所以需要配置ssr: false或者标签,这违反了要求 。

出大问题,改为nuxt3后我不懂得如何正确引用支持vue3的插件

markdown转为html

在网上搜索如何引入markdown相关插件到nuxt3时,然后意外搜索到了 github.com/nuxt-commun… , 以及使用案例 github.com/jyotirmayba…

决定改为使用 markdown-it ( markdown-it.docschina.org/ )

提供了renderer类实例,其中使用render方法,获取 token 流并生成 HTML。

安装 npm install markdown-it

在 script 中

import md from "markdown-it";
const renderer = md();
const article = `
# 一级标题 \n > 这里是文章内容 \n ## 二级标题 \n ### 创建Nuxt3项目 \n ` +
  ' `npx nuxi init nuxt-app `  创建项目  ' +
  '\n' +
  '\n ![猫猫打电脑](https://user-images.githubusercontent.com/71304537/193831026-07cf0de0-48b4-4055-bb8a-97e8aa554704.gif) \n' +
  '\n' +
  '\n' +
  'npx nuxi init nuxt-app \n' +
  '\n' +
  'npm install\n' +
  '\n' +
  'npm run dev\n' +
  '\n' +
  '> 这里写下自己负责的部分实现\n' +
  '\n' +
  '## 文章预览 \n' 
  '```\n' +
  '测试代码快的样式是否可行'
  '```\n';
const articleContent =  renderer.render(article);

使用 要写 class="markdown-body"

<div class="markdown-body" v-html="articleContent"></div>

这样获得了文章的html

获取后端接口

文章添加样式

我放弃了使用github-markdown-css,整了个markdown-css,来适应主题变化。

import 'assets/css/markdown.css';

现在给文章添加markdown的样式 github.com/sindresorhu…

因为考虑到主题化,正好github-markdown-css有light和dark两种样式。

安装 npm install github-markdown-css

在 script 中 import "github-markdown-css/github-markdown-light.css"

使用 class="markdown-body"

处理动态引入(放弃

呃呃呃通过计算属性获取存在theme里的数据,watchEffect,检测样式发生改变

import { useTheme } from '@/composables/useTheme';

import { computed, watchEffect } from '#imports';

const Theme = useTheme();

const theme = computed(() => {

return Theme.theme;

});

watchEffect(()=>{

判断然后,因为是import(github-markdown-css/github-markdown-${ theme }.css)引入样式,所以切换后就会冲突

看网上有些是给个link,href样式

})

掘金的markdown主题 github.com/xitu/juejin…

字节跳动有开源的 Markdown 编辑器ByteMD ,呜呜呜我写完了才知道 😢