封装了一个elementui的确认组件,不过报错了,请大家看看

封装了一个elementui的确认组件,不过报错了,请大家看看

img

img

原因是在then()的回调函数中,this已经不指向Vue实例,所以this上没有$confirm()方法。
修改:
在deleteComment()函数的函数体中,第一行写上const that = this;保存一下this实例,然后在后面的this.$confirm()都换成that.$confirm()

deleteComment: async (username, title) => {
      const that = this;
      await that.$confirm(...) // 后面的this.$confirm都换一下
}
  1. 必须修改Methods的方法使用function,不要使用箭头函数,箭头函数没有this
    const Methods = {
    async deleteComment() {
     this.$message.success("OK?");
    },
    };
    
  2. 在调用时,使用call方式调用,指定delete的this
    await Methods.deleteComment.call(this);
    
    或者是将Methods的方法引入methods中
    async mounted() {
     await this.deleteComment();
    },
    methods: {
     ...Methods
    }
    
    亲测有效

其他的方法,可以考虑使用混入mixin的方式引入这些方法,直接通过this.deleteComment调用

deletecommit上面打印this 看看 。