wangeditor 富文本编辑器简单的使用(vue2 精简版)

41 阅读1分钟

精简版

安装

yarn add @wangeditor/editor 

或者 npm install @wangeditor/editor --save 

yarn add @wangeditor/editor-for-vue 

或者 npm install @wangeditor/editor-for-vue --save

使用代码(代码是组件封装版)

<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar
        id="Toolbar"
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
            style="overflow-y: hidden;"
    :style="{'height':height+'px'}"
            id="editor"
            v-model="htmlValue"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
    />
  </div>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {getAccessToken} from '@/utils/auth'
export default {
  components: { Editor, Toolbar },
    data() {
        return {
            editor: null,
            htmlValue: '',
            toolbarConfig: { 
            },
            editorConfig: { 
                placeholder: '请输入内容...' ,
                uploadFileName: 'file',
                MENU_CONF:{
                        uploadImage:{
                                server: process.env.VUE_APP_BASE_API + '/admin-api/infra/file/upload',
                                fieldName: 'file',
                                maxFileSize: 5 * 1024 * 1024, // 5M
                                headers: {
                                        Authorization: 'Bearer ' + getAccessToken(),
                                        // 'content-type': 'application/json',
                                        'tenant-id':1,
                                },
                                meta:{},
                                withCredentials: true,
                                onBeforeUpload(file){
                                        return file
                                },
                                customInsert(res,insertFn){
                                        insertFn(res.data,'','')
                                }
                        },
                }
            },
            mode: 'default', // or 'simple'
        };
    },
    props:{
			value:{
				type:String,
				default:''
			},
      height:{
				type:Number,
				default:200
			}
		},
		watch:{
			value (){
				this.htmlValue = this.value
			},
			htmlValue (newValue, oldValue){
			  this.$emit('input', newValue)
			},
		},
    created(){
      this.htmlValue = this.value
    },
    methods:{
      onCreated(editor) {
                this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
        },
    },
    beforeDestroy() {
            const editor = this.editor
            if (editor == null) return
            editor.destroy() // 组件销毁时,及时销毁编辑器
    }
}
</script>

<style>

</style>