vue 中 使用百度编辑器 UEditor

时间:2023-03-08 20:39:45

(单页应用,多编辑器也可行)

新建一个Ueditor.vue组件对象,该组件用来封装ueditor,用来进行复用.

<template>
<div>
<!--下面通过传递进来的id完成初始化-->
<script :id="randomId" type="text/plain"></script>
</div>
</template> <script> //需要修改 ueditor.config.js 的路径
//var URL = window.UEDITOR_HOME_URL || ‘/static/ueditor_1/‘; //主体文件引入
import ‘../../static/ueditor_1/ueditor.config.js‘
import ‘../../static/ueditor_1/ueditor.all.min.js‘
import ‘../../static/ueditor_1/lang/zh-cn/zh-cn.js‘
//主体文件引入 export default {
props: {
//配置可以传递进来
ueditorConfig:{}
},
data () {
return {
//每个编辑器生成不同的id,以防止冲突
randomId: ‘editor_‘ + (Math.random() * ),
//编辑器实例
instance: null,
};
},
//此时--el挂载到实例上去了,可以初始化对应的编辑器了
mounted () {
this.initEditor()
}, beforeDestroy () {
// 组件销毁的时候,要销毁 UEditor 实例
if (this.instance !== null && this.instance.destroy) {
this.instance.destroy();
}
},
methods: {
initEditor () {
//dom元素已经挂载上去了
this.$nextTick(() => {
this.instance = UE.getEditor(this.randomId, this.ueditorConfig);
// 绑定事件,当 UEditor 初始化完成后,将编辑器实例通过自定义的 ready 事件交出去
this.instance.addListener(‘ready‘, () => {
this.$emit(‘ready‘, this.instance);
});
});
}
}
};
</script>

Ueditor的使用,通过对组件的监听可以实现回调,把ueditor传回父组件.

<template>
<div id="app">
vue_ueditor
<div>
//此时监听子组件的事件,编辑器实例回调
<Ueditor @ready="editorReady" style="width: 500px;height: 440px;"></Ueditor>
</div> </div>
</template> <script>
import Ueditor from ‘./components/Ueditor‘ export default {
data(){
return{
content:‘‘
}
},
name: ‘app‘,
components: {
Ueditor
},
methods: {
editorReady (instance) {
instance.setContent(‘‘); instance.addListener(‘contentChange‘, () => {
this.content = instance.getContent();
});
},
},
}
</script>

此时封装基本完成,但是上传图片功能还没实现,接下来实现图片上传功能.

// 服务器统一请求接口路径
//在ueditor.config.js里面进行配置,本项目使用的是php后台,后台按照文档配置好,直接通过链接过去即可
//测试发现在本地上传比较慢
//项目打包上传服务器之后,速度回复正常
serverUrl: ‘http://xxx.com/Public/Home/ueditor/php/controller.php‘,

温馨提示 通过设置index.js进行跨域调试(改完需要重新run dev)

dev: {
env: require(‘./dev.env‘),
port: ,
assetsSubDirectory: ‘static‘,
assetsPublicPath: ‘/‘,
//跨域测试接口
proxyTable: {
‘/baseUrl‘: {
target: ‘http://xxx.com/index.php‘,
changeOrigin: true,
pathRewrite: {
‘^/baseUrl‘: ‘‘
}
},
//跨域测试图片上传
‘/baseImgUrl‘: {
target: ‘http://xxx.com‘,
changeOrigin: true,
pathRewrite: {
‘^/baseImgUrl‘: ‘‘
}
}
},

转自URL: http://www.bubuko.com/infodetail-1983484.html