美文网首页
vue和axios中this的问题

vue和axios中this的问题

作者: 放风筝的小小马 | 来源:发表于2018-05-29 23:46 被阅读478次
    /**
         * @description 删除notebook及其下面的文章
         * @param
         * @return
         */
        deleteNotebook(index) {
          axios({
            url: this.$appConfig.api.notebooks.remove,
            method: 'DELETE',
            data: JSON.stringify({
              id: this.notebooksList[index].id,
            }),
          })
            .then((response) => {
              if (response.data.status === 200) {
                debugger
                this.notebooksList.splice(index, 1);
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                });
              } else {
                throw new Error(response.msg);
              }
            })
            .catch((error) => {
              console.error(`删除失败:${error.message}`);
            });
        },
    

    如上代码中,打印this时,始终是undefined,但是又能够调用绑定在vue实例上的$message方法,
    解决方法:
    **在调用axios之前先保存this,const that = this,然后在回调中使用that代替this

    相关文章

      网友评论

          本文标题:vue和axios中this的问题

          本文链接:https://www.haomeiwen.com/subject/lkmzjftx.html