项目场景:
项目场景:UEditor富文本插件在VUE这种单页面的项目中刷新以后重新创建实例失败并且报错,一度想换其他富文本。
问题描述
UEditor富文本插件只允许首次加载页面的时候创建实例,但是我们在VUE项目里面使用时避免不了局部刷新这种场景,这种老的插件就很让人蛋疼。
网上其他的解决方法说的信誓旦旦如:
// 在 UE.getEditor后面再追加一个方法render.
UE.getEditor('选择器').render('选择器');
//或者先调用UE.delEditor删除后再执行。
UE.delEditor('选择器');
UE.getEditor('选择器');
这种实测没卵用!!!!
原因分析:
其实分析的原因还是和上面的解决方法分析的原因是一致的。
UE.getEditor = function (id, opt) {
var editor = instances[id];
if (!editor) {
editor = instances[id] = new UE.ui.Editor(opt);
editor.render(id);
}
return editor;
};
UE.delEditor = function (id) {
var editor;
if (editor = instances[id]) {
editor.key && editor.destroy();
delete instances[id]
}
};
调用 UE.getEditor 的时候先从instances取出,不存在了再实例化,第二次调用的时候还是调用了instances中那个,并没有重新实例化。
完美解决方案:
考虑到每次实例化的时候都会记录实例到instances这个对象中去,所以是不是每次刷新需要重新实例化的时候可以再次push新的实例到instances中呢,如下场景:
<template>
<div :id="ueditorKey"></div>
</template>
<script>
export default {
name:'ueditor',
data () {
return {
ueditorKey: null,
ueditor: null
}
},
created () {
// 每次都生成一个不一样名称的实例
this.ueditorKey = 'editor'+new Date().getTime()
},
mounted () {
this.ueditor = UE.getEditor(this.ueditorKey)
},
beforeDestroy () {
UE.delEditor(this.ueditorKey)
}
}
</script>
这样就完美解决这种操蛋问题了,其实无论是vue或者是其他的框架,也可以用类似的想法解决这个问题。