[前端] wang 富文本 vue3
官方链接
https://www.npmjs.com/package/@wangeditor-next/editor-for-vue
<template><div style="border: 1px solid #ccc"><Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" /><Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"@onCreated="handleCreated" /></div><div v-html="valueHtml"></div>
</template><script>
import '@wangeditor/editor/dist/css/style.css'; // 引入 cssimport { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';export default {components: { Editor, Toolbar },setup() {// 编辑器实例,必须用 shallowRefconst editorRef = shallowRef();// 内容 HTMLconst valueHtml = ref('<p>hello</p>');// 模拟 ajax 异步获取内容onMounted(() => {setTimeout(() => {valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>';}, 1500);});const toolbarConfig = {excludeKeys: ['uploadImage', // 隐藏图片上传按钮(使用粘贴功能)'group-video' // 隐藏视频相关功能]};const editorConfig = {placeholder: '请输入内容...',uploadImgShowBase64: true,MENU_CONF: {uploadImage: {server: null,pasteImage: true,base64LimitSize: 5 * 1024 * 1024}}};// 组件销毁时,也及时销毁编辑器onBeforeUnmount(() => {const editor = editorRef.value;if (editor == null) return;editor.destroy();});const handleCreated = (editor) => {editorRef.value = editor; // 记录 editor 实例,重要!};return {editorRef,valueHtml,mode: 'default', // 或 'simple'toolbarConfig,editorConfig,handleCreated,};},
};
</script><style lang="scss" scoped></style>
改造
<template><div style="border: 1px solid #ccc"><Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" /><Editorstyle="height: 500px; overflow-y: hidden;"v-model="valueHtml":defaultConfig="editorConfig"mode="default"@onCreated="handleCreated"/></div><div v-html="valueHtml"></div>
</template><script>
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';export default {components: { Editor, Toolbar },data() {return {editorRef: null, // 编辑器实例引用valueHtml: '<p>hello</p>', // 内容toolbarConfig: { // 工具栏配置excludeKeys: ['uploadImage', 'group-video']},editorConfig: { // 编辑器配置placeholder: '请输入内容...',uploadImgShowBase64: true,MENU_CONF: {uploadImage: {server: null,pasteImage: true,base64LimitSize: 5 * 1024 * 1024}}}}},mounted() {// 模拟异步数据setTimeout(() => {this.valueHtml = '<p>模拟 Ajax 异步设置内容</p>'}, 1500)},beforeUnmount() {// 组件销毁时销毁编辑器if (this.editorRef) this.editorRef.destroy()},methods: {handleCreated(editor) {this.editorRef = editor // 保存编辑器实例}}
}
</script>
如果设置read only
// 只读预览编辑器配置previewEditorConfig: {readOnly: true, // 关键:设置为只读模式autoFocus: false,scroll: false,MENU_CONF: {}}