You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue.js项目中引入并使用外部JavaScript库wysihtml

Vue.js项目集成wysihtml库解决方案

原有操作的问题

  • 引入方式不适配现代Vue工程化项目:使用bower路径硬引入的方式仅适用于传统静态HTML项目,vue-cli、vite等工具构建的Vue项目会做资源打包,直接写bower_components的相对路径大概率会出现资源找不到的问题。
  • 初始化时机错误:wysihtml需要绑定真实DOM节点,如果在created等DOM还未生成的生命周期调用初始化方法,会找不到对应节点导致初始化失败。

可行性说明

wysihtml是原生JS开发的无框架依赖富文本库,完全可以在Vue项目中正常使用,不存在兼容性冲突。

具体集成步骤

步骤1:安装依赖

优先使用npm安装包,无需使用bower:

npm install wysihtml --save

步骤2:单文件组件内引入使用

示例代码如下:

<template>
  <div class="editor-container">
    <!-- 编辑器工具栏 -->
    <div id="wysihtml-toolbar" style="margin-bottom: 10px;">
      <button data-wysihtml5-command="bold">加粗</button>
      <button data-wysihtml5-command="italic">斜体</button>
      <button data-wysihtml5-command="insertUnorderedList">无序列表</button>
      <button data-wysihtml5-command="insertOrderedList">有序列表</button>
    </div>
    <!-- 编辑器输入区域 -->
    <textarea id="wysihtml-editor" placeholder="请输入内容"></textarea>
  </div>
</template>

<script>
import wysihtml from 'wysihtml'
import 'wysihtml/dist/wysihtml.css'

export default {
  name: 'WysihtmlEditor',
  data() {
    return {
      editorInstance: null
    }
  },
  mounted() {
    // 必须在mounted生命周期初始化,保证DOM已渲染完成
    this.editorInstance = new wysihtml.Editor('wysihtml-editor', {
      toolbar: 'wysihtml-toolbar',
      parserRules: wysihtmlParserRules
    })
  },
  // Vue3项目用beforeUnmount,Vue2项目替换为beforeDestroy
  beforeUnmount() {
    // 组件销毁前销毁实例,避免内存泄漏
    if (this.editorInstance) {
      this.editorInstance.destroy()
    }
  },
  methods: {
    // 获取编辑器内容
    getContent() {
      return this.editorInstance.getValue()
    },
    // 设置编辑器内容
    setContent(content) {
      this.editorInstance.setValue(content)
    }
  }
}
</script>

补充说明

  • 工具栏功能可根据需求自行扩展,仅需要给对应按钮加上对应data-wysihtml5-command属性即可,无需额外写交互逻辑。
  • 如果是传统HTML引入Vue的非工程化项目,可以直接把wysihtml的js、css资源放到静态资源目录,用script标签引入后,依然按照上述逻辑在mounted生命周期初始化即可。

内容的提问来源于stack exchange,提问作者JohnW2Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:24:03