Files
2022-07-21 17:29:19 +08:00

136 lines
2.8 KiB
Vue

<template>
<div :style="`border: 1px solid #ccc; width: ${width}`">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editorRef"
:defaultConfig="toolbarConfig"
:mode="mode"
/>
<Editor
:style="`min-height: ${minHeight}; height: ${height} overflow-y: hidden`"
v-model="valueHtml"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="handleCreated"
@onChange="handleChange"
/>
</div>
</template>
<script>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
onBeforeUnmount,
onMounted,
ref,
shallowRef,
toRefs,
watch,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
export default {
components: { Editor, Toolbar },
props: {
modelValue: {
type: String,
default: "",
},
minHeight: {
type: String,
default: "150px",
},
height: {
type: String,
default: "320px",
},
width: {
type: String,
default: "100%",
},
focus: {
type: Boolean,
default: false,
},
mode: {
type: String,
default: "default",
},
readonly: {
type: Boolean,
default: false,
},
},
setup(props, context) {
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
watch(
() => props.modelValue,
(val) => {
valueHtml.value = val;
},
{ immediate: true }
);
const { height } = toRefs(props);
const toolbarConfig = {
toolbarKeys: [
"bold",
"underline",
"italic",
"through",
"color",
"bgColor",
"fontSize",
"fontFamily",
"lineHeight",
// "emotion",
// "redo",
// "undo",
],
};
const editorConfig = {
placeholder: "请输入内容...",
autoFocus: props.focus,
maxLength: 140,
readOnly: props.readonly,
};
onMounted(() => {
// console.log(editorRef.value.getConfig());
});
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value;
if (editor == null) return;
editor.destroy();
});
const handleCreated = (editor) => {
editorRef.value = editor; // 记录 editor 实例,重要!
};
const handleChange = (editor) => {
if (editor.getHtml() === "<p><br></p>") {
context.emit("update:modelValue", "");
} else {
context.emit("update:modelValue", editor.getHtml());
}
};
return {
editorRef,
valueHtml,
mode: "default", // 或 'simple'
toolbarConfig,
editorConfig,
height,
handleCreated,
handleChange,
};
},
};
</script>