vue + wangeditor封装富文本组件

一、介绍

wangEditor —— 轻量级 web 富文本编辑器,配置方便,使用简单。

二、下载

NPM


	npm i wangeditor --save
	

安装后几行代码即可创建一个编辑器:


	import E from "wangeditor"
	const editor = new E("#div1")
	editor.create()
	

CDN


	<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"></script>
	<script type="text/javascript">
	
	  const E = window.wangEditor
	  const editor = new E("#div1")
	  editor.create()
	  
	</script>

三、使用

  1. 在目录 src/components/editor 文件夹下新建富文本组件 Editor.vue

	<template>
	  <div id="editor">
	    <div id="editorElem" style="text-align: left"></div>
	  </div>
	</template>
	
	<script>
	
	import E from "wangeditor";
	
	export default {
    
    
	
	  data() {
    
    
	    return {
    
    
	      editor: null, // 富文本示例
	      editorContent: "", // 富文本内容
	    };
	  },
	  
	  props: ["htmlContent"], // 父组件传递过来的富文本默认内容
	  
	  methods: {
    
    
	
	    // 初始化富文本
	    initEditor() {
    
    
	      this.editor = new E('#editorElem');
	
	      // 监听富文本内容更改
	      this.editor.config.onchange = (html) => {
    
    
	        this.editorContent = html;
	        // 将内容发送给父组件
	        this.$emit('changeHtmlContent', html)
	      };
	
	      // 设置高度
	      // this.editor.config.height = 500
	
	      // 图片上传逻辑
	      this.editor.config.customUploadImg = function (resultFiles, insertImgFn) {
    
    
	        // 这里将图片resultFiles上传到服务器,拿到返回值imgUrl
	        console.log(resultFiles);
	        // 这里将imgUrl插入到富文本
	        // insertImgFn(imgUrl)
	      }
	      
	      // 创建富文本实例
	      this.editor.create();
	
	      // 设置富文本内容
	      this.editor.txt.html(this.htmlContent);
	
	    },
	
	  },
	  
	  mounted() {
    
    
	    this.initEditor()
	  },
	  
	};
	
	</script>
	
	<style scoped></style>

  1. 在需要使用的地方

	<template>
		<div>
      		<Editor :htmlContent="htmlContent" @changeHtmlContent="changeHtmlContent"></Editor>
		</div>
	</template>
	
	<script>
		import Editor from '@/components/editor/Editor.vue';
		export default {
    
    
			components: {
    
     Editor },
			data() {
    
    
				return {
    
    
					htmlContent: "", // 富文本内容,可设置默认值
				}
			},
			methods: {
    
    
				// 富文本内容更改后赋值
				changeHtmlContent(html) {
    
    
					this.htmlContent = html
					console.log(this.htmlContent);
				},
			}
		}
	</script>

更多

更多使用功能请参考 官网文档

猜你喜欢

转载自blog.csdn.net/weixin_43923659/article/details/120547149