文档地址
官网:www.wangeditor.com/v5/toolbar-…
github: github.com/wangeditor-…
安装
yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save
yarn add @wangeditor/editor-for-vue@next
# 或者 npm install @wangeditor/editor-for-vue@next --save
使用方式
<script lang="ts" setup>
import { reactive, ref, shallowRef, onBeforeUnmount } from 'vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
const editorRef = shallowRef();
const model = ref({
content: '',
});
const handleCreated = (editor: any) => {
editorRef.value = editor; // 记录 editor 实例,重要!
// 查看所有工具栏key
console.log(editorRef.value.getAllMenuKeys());
};
const toolbarConfig = reactive({
// 排除不需要的工具栏, 我只需要简单的文字排版 并且小程序不支持Dom渲染,css样式会失效
excludeKeys: [
'uploadImage',
'insertVideo',
'uploadVideo',
'group-image',
'insertLink',
'codeBlock',
// 这个其实我用不上 但是示例图片中是有的
// 'blockquote', //引用
// 'insertTable', // 插入表格
// 'todo', //代办
],
// 插入工具栏
insertKeys: {
index: 15,
keys: ['indent', 'delIndent'], //文本缩进
},
});
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value;
if (editor == null) return;
editor.destroy();
});
</script>
<template>
<Toolbar :default-config="toolbarConfig" :editor="editorRef" mode="simple" />
<Editor
v-model="model.content"
style="border: 1px solid #ccc; min-height: 180px"
:default-config="{ placeholder: '请输入内容...' }"
mode="simple"
@on-created="handleCreated"
/>
</template>
内容渲染
后台渲染
需要渲染页面
// 引入css
import '@wangeditor/editor/dist/css/style.css';
<template>
<!--类名需要注意 w-e-text-container -->
<div class="w-e-text-container">
<!-- data-slate-editor -->
<div data-slate-editor v-html="content"></div>
</div>
</template>
小程序代码
// editor.less 样式内部我添加了 w-e-text-container-deep类名
// editor.less --- /deep/.w-e-text-container-deep { ...复制过来的样式 }
<view class="detail_content w-e-text-container-deep">
<view v-html="content" class="w-e-text-container"></view>
</view>
<style lang="less" scoped>
// css样式
@import './editor.less';
</style>
H5渲染
开发者工具预览! 哦豁
微信小程序不支持渲染dom格式,使用的rich-text渲染,类名样式无法关联...
跨端的富文本处理方案:ask.dcloud.net.cn/article/357…
web-view: uniapp.dcloud.net.cn/component/w…
解决方案: 使用 web-view 但是需要将渲染页面打包成H5发布,代价有点大,所以最后我只保留了文本格式工具 使用u-parse组件渲染,无需引入css样式。
<template>
<u-parse :content="content" :tagStyle="htmlStyle"></u-parse>
</template>
<script>
export default {
data() {
return {
htmlStyle: {
// 字符串的形式,标签样式调整成富文本编辑样式
// 正常margin是10px,但是我嫌弃太宽了 调整了一下
p: 'margin:5px 0',
h1: 'margin: 20px 0',
h2: 'margin: 20px 0',
h3: 'margin: 20px 0',
li: `cursor: pointer;
padding: 7px 0 7px 0;
position: relative;
white-space: nowrap`
}
}
}
}
</script>
小程序渲染有更好的解决方案的话麻烦指导,感激不尽