在vue-froala-wysiwyg事件中调用Vue组件方法失败如何解决?
问题根因
froala编辑器的事件回调默认将内部this绑定到编辑器自身实例,你在回调内部无法直接拿到当前Vue组件的实例,之前尝试访问this.$parent、this.el等属性不存在就是因为此时的this根本不是Vue相关实例。另外你触发的parent.actionUser is not a function报错,是因为代码中没有定义parent这个变量,属于未定义变量调用方法导致的错误。
解决方案
方案1:在data作用域提前缓存Vue组件实例(改动最小,推荐)
在data()函数的最顶部先把当前Vue组件的this存为变量,回调里直接用这个变量调用组件方法即可:
data() { // 提前缓存当前Vue组件实例 const vm = this return { currentRoom: null, // 其他原有属性... froalaEditorConfig: { events: { initialized: function () { console.log('froalaEditorConfig initialized') }, 'contentChanged': function () { // 这里this还是编辑器实例,可以直接调用编辑器API拿内容 const inputContent = this.html.get() // 用提前缓存的vm变量调用组件自定义方法 vm.actionUser(inputContent) } } } } }
方案2:使用箭头函数绑定外层作用域this
你也可以将回调改写为箭头函数,箭头函数不会绑定自身的this,会继承外层作用域的this也就是当前Vue组件实例。需要注意此时回调内的this不再是编辑器实例,如果要获取编辑器内容,可以给froala组件加ref属性来访问编辑器实例:
- 模板中给froala组件添加ref:
<froala ref="froalaEditor" :config="froalaEditorConfig" v-model="editorContent" ></froala>
- 改写事件回调为箭头函数:
froalaEditorConfig: { events: { 'contentChanged': () => { // 这里this是当前Vue组件实例 const inputContent = this.$refs.froalaEditor.editor.html.get() this.actionUser(inputContent) } } }
内容的提问来源于stack exchange,提问作者mstdmstd
相关产品推荐
相关产品推荐

