Vue项目中使用wangEditor富文本输入框(推荐)
发布时间:2026/9/13 20:11:20 作者:尧图编辑部 阅读量:1,286
)
vue中安装wangEditorcnpm install wangeditor创建公用组件在src/vue/components文件夹中创建wangEditor.vuewangEditor.vue 封装组件源码template langhtml div :class$options.name :loadingloading v-loadingloading :element-loading-textelementLoadingText radius-loading v-clickoutsideclickoutside div reftoolbar classtoolbar/div div refwangEditor classtext/div /div /template script import clickoutside from element-ui/src/utils/clickoutside; import E from wangEditor; // 【重点菜单类写在script顶层不要写在mounted里面】■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ const { $, BtnMenu } E; // 工具函数从当前节点向上查找看是否存在指定标签 function findParentTag($node, tagName) { if (!$node) return null; let cur $node.elems[0]; while (cur) { if (cur.tagName cur.tagName.toUpperCase() tagName.toUpperCase()) { return cur; } cur cur.parentNode; } return null; } function tryChangeActive({ tagName sup } {}, _this) { const editor _this.editor; let selection editor.selection; const hasTag !!findParentTag(selection.getSelectionContainerElem(), tagName); // 手动操作class替代 this.active() if (hasTag) { _this.$elem.addClass(w-e-active); } else { _this.$elem.removeClass(w-e-active); } } function clickHandler({ tagName sup, editor } {}) { if (!editor.selection.isSelectionEmpty()) { // 原生API拿到选中HTML支持保留加粗/颜色 let selection editor.selection; const hasTag !!findParentTag(selection.getSelectionContainerElem(), tagName); const selectedHtml selection.getSelectionText(); if (hasTag) { editor.cmd.do(insertHTML, selectedHtml); } else { let script ; switch (tagName) { case sup: script superscript; break; case sub: script subscript; break; default: } editor.cmd.do(script); } } } // 上标菜单 class SupMenu extends BtnMenu { constructor(editor) { const $elem $(div classw-e-menu>template div wangEditor styleheight: 100% v-modelwangEditorDetail :placeholder输入文章标题 :isClearisClear changewangEditorChange /wangEditor /div /template script import wangEditor from /vue/components/admin/wangEditor; export default { components: { wangEditor }, data() { return { isClear: false, //设置为true的时候这个可以用this.wangEditorDetail来替代 wangEditorDetail: , }; }, mounted() { this.wangEditorDetail wangEditorDetail默认值; //设置富文本框默认显示内容 }, methods: { wangEditorChange(val) { console.log(val); }, }, }; /script相关知识点JavaScript 模拟光标全选选中一段文字JavaScript 模拟光标全选选中一段文字-CSDN博客函数它接受一个DOM节点作为参数然后选择这个节点的全部内容。在现代浏览器中它使用。在JavaScript中如果你想要通过编程方式选择一段文本你可以使用。使用时只需传入你想要选中的元素即可。在旧版IE浏览器中它使用。https://blog.csdn.net/qq_37860634/article/details/140252939