Vue3集成TipTap Editor时如何将Vue实例作用域传入事件回调
问题原因
普通函数声明的onFocus、onBlur回调会被TipTap绑定到Editor实例自身,所以回调内部的this指向Editor而不是Vue组件实例,自然访问不到$refs属性。
解决方案:改用箭头函数绑定外层作用域
箭头函数不会创建自己的this,会继承外层执行上下文的this,也就是mounted钩子中的Vue组件实例,直接修改回调的声明方式即可:
修改后的业务代码如下:
mounted(){ // this.store.methods.TextAreaAdjust(this.$refs.itemParagraph); this.editor = new Editor( { extensions: [ StarterKit.configure({ history:true, }), Highlight, ], content: this.modelValue.itemData.paragraph, onUpdate: () => { this.modelValue.itemData.paragraph=this.editor.getHTML() }, // 改为箭头函数继承外层this onFocus: () => { console.log('focus fired') this.$refs.editMenu.style.display="flex" }, // 改为箭头函数继承外层this onBlur: () => { console.log('blur fired') this.$refs.editMenu.style.display="none" } }) },
备选方案:提前缓存Vue实例指向
如果不习惯用箭头函数,也可以在mounted开头先缓存Vue组件的this指向,回调中直接使用缓存的变量访问实例属性:
mounted(){ const vm = this // 提前缓存Vue组件实例 this.editor = new Editor( { // 其他配置保持不变 onFocus(){ vm.$refs.editMenu.style.display="flex" }, onBlur(){ vm.$refs.editMenu.style.display="none" } }) }
内容的提问来源于stack exchange,提问作者Harvey Mushman
相关产品推荐
相关产品推荐

