Vue项目中使用wangEditor富文本输入框(推荐)
2026/9/13 20:11:17 网站建设 项目流程

vue中安装wangEditor

cnpm install wangeditor

创建公用组件:在src/vue/components文件夹中创建wangEditor.vue

wangEditor.vue 封装组件源码

<template lang="html"> <div :class="$options.name" :loading="loading" v-loading="loading" :element-loading-text="elementLoadingText" radius-loading v-clickoutside="clickoutside" > <div ref="toolbar" class="toolbar"></div> <div ref="wangEditor" class="text"></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 class="w-e-menu"><template> <div> <wangEditor style="height: 100%" v-model="wangEditorDetail" :placeholder="`输入文章标题`" :isClear="isClear" @change="wangEditorChange" ></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

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询