【问题标题】:Error in v-on handler (Promise/async): TypeError: _this.$refs.editor.save is not a functionv-on 处理程序中的错误(Promise/async):TypeError:_this.$refs.editor.save 不是函数
【发布时间】:2020-12-22 08:42:47
【问题描述】:

大家好,我需要帮助,当我点击我的 @click="save" 按钮时,它应该运行保存功能,但我得到了错误:

v-on 处理程序中的错误(Promise/async):TypeError: _this.$refs.editor.save 不是函数

这里是保存功能

  async save(){
        this.$refs.editor.save()   
    }

【问题讨论】:

    标签: javascript laravel vue.js


    【解决方案1】:

    当你在组件中使用refs 时,它会返回一个数组。也许你应该使用数组的第一个元素。

    async save(){
      this.$refs.editor[0] && this.$refs.editor[0].save()   
    }
    

    确保您的组件已安装。

    再见

    【讨论】:

    • 是的,谢谢你的想法,现在它说保存未定义
    • "TypeError: 无法读取未定义的“保存”属性"
    • 你能上传一个小提琴吗?
    • 异步保存(){ this.$refs.editor[0].save() }
    • 感谢警告:“确保您的组件已安装”这对我很有帮助!
    【解决方案2】:

    也许不相关,但最终遇到了同样的问题。这篇文章和@mateonunez 的回答帮助我解决了我的问题,所以我将把解决方案留给未来的读者。

    我正在使用 jest 来测试单击按钮时是否出现模式。

     let openModalBtn = wrapper.find('button[id="openModal"]');
     expect(openModalBtn.exists()).toBe(true); // OK
     expect(openModalBtn.is("button")).toBe(true); // OK
     await deleteBtn.trigger("click"); // BANG
    

    导致:

    [Vue warn]: Error in v-on handler (Promise/async): "TypeError: this.$refs.confirmDialogue[0].show is not a function"
    

    问题是我使用的是shallowMount

    // not good
    describe("some test", () => {
      let wrapper;
      beforeEach(() => {
        wrapper = shallowMount(MyComponent, {...});
      });
    
    

    MyComponent 的某个时刻,它需要执行以下操作:

    ...
      methods: {
        openModal() {
          await this.$refs.confirmDialogue[0].show();
          ...
        },
    

    因此this.$refundefined 的身份出现。

    改用mount

    // good
    describe("some test", () => {
      let wrapper;
      beforeEach(() => {
        wrapper = mount(MyComponent, {...});
      });
    
    

    允许我单击该按钮并在 wrapper.html() 中找到存根。

    【讨论】: