需求介绍
今天收到一个需求,需要更改插入附件的文字提示,要求提示大小限制(500M),也就是tooltip,修改前后的效果如图所示。
源码
<template>
<div>
<!-- 将编辑器绑定到 textarea -->
<textarea ref="editor" :id="editorId"></textarea>
</div>
</template>
<script>
import { Editor } from '@tinymce/tinymce-vue';
export default {
components: {
Editor,
},
data() {
return {
editorId: 'my-editor', // 编辑器 ID
};
},
mounted() {
tinymce.init({
selector: `#${this.editorId}`,
plugins: 'attachment',
#步骤1:在toolbar中添加上传附件的按钮->attachment
toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | attachment',
});
#步骤3:在dom加载完毕后延迟200毫秒执行funcModifyTooltip,具体延迟时间需要根据实际项目调整
this.$nextTick(()=>{
setTimeout(()=>{
this.funcModifyTooltip()},200)
})
},
methods: {
#步骤2:实现修改函数,其中一些具体的参数请根据实际开发来
funcModifyTooltip(){
#tinymce工具栏的className是tox-toolbar__group,此时获取到的toolbarGroup是一个htmlCollection
var toolbarGroup = document.getElementsByClassName('tox-toolbar__group');
if (toolbarGroup) {
#只有一个className是tox-toolbar__group的dom元素,所以是item(0)
var tox_toolbar__group = toolbarGroup.item(0)
if(tox_toolbar__group){
#再根据className是button的类名来获取工具栏里的所有按钮
var toolbar_buttons = tox_toolbar__group.getElementsByTagName('button')
if (toolbar_buttons){
#我这里上传附件是第11个按钮,所以是item(10)
var attachment_button = toolbar_buttons.item(10)
if(attachment_button){
#最后设置title属性来更改想要的文字提示
attachment_button.setAttribute('title','插入附件(最大500M)')
}
}
}
}
},
},
};
</script>
<style>
/* 根据需要进行样式定义 */
</style>
方法介绍
1、toolbar添加上传附件的按钮
tinymce初始化时,在toolbar中添加attachment(上传附件)的按钮
2、实现修改上传附件的文字提示的函数
可以在method中定义 funcModifyTooltip函数,该函数通过获取document的dom节点来更改按钮的提示文字
3、在mounted钩子函数中调用 funcModifyTooltip函数
调用时需要使用setTimeout函数,根据页面加载的速度设置延迟调用时间,只用nextTick函数可能无效。
注意踩坑
1、为什么不直接使用nextTick函数,还需要使用setTimeout函数?
如果只使用nextTick函数,在我们获取DOM元素(类名获取元素)也就是步骤2中toolbarGroup(接口htmlCollection)的时候,控制台中可以打印出来值,但是length长度为0,htmlcollection对象使用item返回null,导致我们获取不到item(0),类似这种报错:https://blog.csdn.net/Yukinoshita_kino/article/details/124130452
总之代表这个时候可能dom还没有完全加载完成,所以需要用到setTimeout函数,明明已经使用了nextTick,具体原因我也不清楚。参考:vue中拿不到第一次数据,只能从第二次拿的情况
2、setTimeout无效的情况
setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式,只接受匿名函数,而且setTimeout 内部对this的指向是有问题的,当涉及到this的时候需要改变写法。所以我们在setTimeout中使用了()=>。参考:setTimeout()、setInterval()不起作用?答案在这里
如果有什么疑问,欢迎在评论区讨论!