You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:45:01