Vue中使用 vditor 使用详细步骤,代码以及注释,效果图

使用 Vditor 在 Vue 中编辑并展示 Markdown 文本的步骤如下:

1. 安装 Vditor:使用 npm 安装 Vditor 插件:

npm install --save vditor

2. 导入 Vditor:在需要使用 Vditor 的 Vue 组件中导入 Vditor 插件:

import Vditor from 'vditor';

3. 创建 Vditor 实例:在 Vue 组件的 created 生命周期钩子函数中创建 Vditor 实例,并将其挂载到 Vue 实例的 data 中:

created() {
  this.vditor = new Vditor('vditorContainer');
}

4. 添加 Vditor 容器:在 Vue 组件的模板中添加一个与 Vditor 实例绑定的容器:

<template>
  <div id="vditorContainer"></div>
</template>

5. 设置 Vditor 配置:根据需要设置 Vditor 的配置项,例如编辑器模式(编辑或预览)、主题、语言、提示功能等。可以在 created 生命周期钩子函数中调用 Vditor 的 setOption 方法设置配置项:

created() {
  this.vditor = new Vditor('vditorContainer');
  this.vditor.setOption({
    mode: 'wysiwyg',
    theme: 'classic',
    lang: 'zh_CN',
    hint: {
      emoji: {
        '+1': '',
        '-1': '',
        '100': '',
        // 其他自定义 emoji
      },
      emojiTail: ' ',
      at: ['user1', 'user2', 'user3'],
      // 其他自定义提示
    }
  });
}

6. 获取 Markdown 文本:通过 Vditor 实例的 getValue 方法获取编辑器中的 Markdown 文本。

methods: {
  getMarkdown() {
    const markdown = this.vditor.getValue();
    console.log(markdown);
  }
}

7. 展示 Markdown 文本:将获取到的 Markdown 文本转换为 HTML 并在页面中展示。可以使用第三方的 Markdown 解析库,如 markdown-it。

<template>
  <div>
    <div id="vditorContainer"></div>
    <div v-html="html"></div>
  </div>
</template>

<script>
import Vditor from 'vditor';
import MarkdownIt from 'markdown-it';

export default {
  data() {
    return {
      vditor: null,
      markdown: '',
      html: ''
    };
  },
  created() {
    this.vditor = new Vditor('vditorContainer');
  },
  methods: {
    getMarkdown() {
      this.markdown = this.vditor.getValue();
      const md = new MarkdownIt();
      this.html = md.render(this.markdown);
    }
  }
}
</script>

你可能感兴趣的:(vue.js,前端,javascript)