最近在vue項目中需要使用富文本編輯器,於是將Ueditor集成進來,作為公共組件。 在線預覽:https://suweiteng.github.io/vue2-management-platform/#/editor
項目地址:https://github.com/suweiteng/vue2-management-platform 記得在右上角點個贊哦~
1.放入靜態資源並配置
首先把官網下載的Ueditor資源,放入靜態資源src/static中。 修改ueditor.config.js中的window.UEDITOR_HOME_URL配置,如下圖:
2.引入
在main.js中引入
import '../static/UE/ueditor.config.js'
import '../static/UE/ueditor.all.min.js'
import '../static/UE/lang/zh-cn/zh-cn.js'
import '../static/UE/ueditor.parse.min.js'
3.開發公共組件
開發公共組件,可設置填充內容defaultMsg,配置信息config(寬度和高度等),並提供獲取內容的方法。
<template>
<div>
<script id="editor" type="text/plain"></script>
</div>
</template>
<script>
export default {
name: 'UE',
data () {
return {
editor: null
}
},
props: {
defaultMsg: {
type: String
},
config: {
type: Object
}
},
mounted() {
const _this = this;
this.editor = UE.getEditor('editor', this.config); // 初始化UE
this.editor.addListener("ready", function () {
_this.editor.setContent(_this.defaultMsg); // 確保UE加載完成后,放入內容。
});
},
methods: {
getUEContent() { // 獲取內容方法
return this.editor.getContent()
}
},
destroyed() {
this.editor.destroy();
}
}
</script>
4.使用
當我們需要使用富文本編輯器時,直接調用公共組件即可
<template>
<div class="components-container">
<div class="info">UE編輯器示例<br>需要使用編輯器時,調用UE公共組件即可。可設置填充內容defaultMsg,配置信息config(寬度和高度等),可調用組件中獲取內容的方法。</div>
<button @click="getUEContent()">獲取內容</button>
<div class="editor-container">
<UE :defaultMsg=defaultMsg :config=config ref="ue"></UE>
</div>
</div>
</template>
<style>
.info{
border-radius: 10px;
line-height: 20px;
padding: 10px;
margin: 10px;
background-color: #ffffff;
}
</style>
<script>
import UE from '../../components/ue/ue.vue';
export default {
components: {UE},
data() {
return {
defaultMsg: '這里是UE測試',
config: {
initialFrameWidth: null,
initialFrameHeight: 350
}
}
},
methods: {
getUEContent() {
let content = this.$refs.ue.getUEContent();
this.$notify({
title: '獲取成功,可在控制台查看!',
message: content,
type: 'success'
});
console.log(content)
}
}
};
</script>
效果如下:
##5.報錯 ###ESlint報錯 eslint報錯的參考請評論4L 5L ###嚴格模式報錯 部分人使用時出現以下報錯: Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them...
這個問題是因為項目中的使用的babel默認添加了use strict造成,可參考 https://segmentfault.com/q/1010000007415253 我采用的是鏈接中答案的第三種方式:添加了babel-plugin-transform-remove-strict-mode,並在.babelrc里添加下列代碼
{
"plugins": ["transform-remove-strict-mode"]
}
然后就沒問題了。