【问题标题】:How to access local component variable from a callback in vue?如何从 vue 中的回调中访问局部组件变量?
【发布时间】:2024-05-03 00:30:02
【问题描述】:

我正在尝试使用 api rest 命令设置我的 components 变量。我想通过一个名为 handleResponse() 的文件中的函数来处理所有响应,如下所示。

// api/tools/index.js
function handleResponse (promise, cb, cbError) {
  var cbErrorRun = (cbError && typeof cb === "function") 

  promise.then(function (response) {
    if (!response.error) {
      cb(response)
    }
    else if (cbErrorRun) {
      cbError(response)
    }
  }).catch(function (error) {
    console.log(error)
    if (cbErrorRun) {
      var responseError = {
        "status": 404,
        "error": true,
        "message": error.toString()
      }
      cbError(responseError)
    }
  })
}
export {handleResponse}

在我的组件文件中我有这个

.... More above....
<script>
import { fetchStock } from '@/api/stock'    

  export default {

    data () {
      return {
        stock: {},
        tabs: [
          {
            title: 'Info',
            id: 'info'
          },
          {
            title: 'Listings',
            id: 'listings'
          },
          {
            title: 'Company',
            id: 'company'
          }
        ],
      }
    },
    validate ({params}) {
      return /^\d+$/.test(params.id)
    },
    created: function() {
      var params = {'id': this.$route.params.stockId}
      //this.$route.params.stockId}
      fetchStock(
        params,
        function(response) { //on successful data retrieval
          this.stock = response.data.payload // payload = {'name': test123}
          console.log(response)
        },
        function(responseError) { //on error
          console.log(responseError)
        }
      )
    }
  }
</script>

当前代码给了我这个错误:“Uncaught (in promise) TypeError: Cannot set property 'stock' of undefinedAc”。我认为发生这种情况是因为我在 fetchStock 函数中传递的回调中不再可以访问“this”。如何在不更改当前 handleResponse 布局的情况下解决此问题。

【问题讨论】:

    标签: vue.js callback vuejs2 vue-component axios


    【解决方案1】:

    你可以试试这个技巧

      created: function() {
          var params = {'id': this.$route.params.stockId}
          //this.$route.params.stockId}
          var self = this;
          fetchStock(
            params,
            function(response) { //on successful data retrieval
              self.stock = response.data.payload // payload = {'name': test123}
              console.log(response)
            },
            function(responseError) { //on error
              console.log(responseError)
            }
          )
        }
    

    【讨论】:

    • 哇,谢谢,我一直在尝试一切并撕毁我的头发。
    【解决方案2】:

    您可以使用箭头函数进行回调,因为箭头函数维护并使用其包含范围的this

    created: function() {
          var params = {'id': this.$route.params.stockId}
          //this.$route.params.stockId}
    
          fetchStock(
            params,
            (response) => { //on successful data retrieval
              self.stock = response.data.payload // payload = {'name': test123}
              console.log(response)
            },
            (responseError) => { //on error
              console.log(responseError)
            }
          )
        }
    

    或者您可以在回调之前分配const vm = this n 方法的开头,就像这样。

    vm 代表“视图模型”

      created: function() {
          var params = {'id': this.$route.params.stockId}
          //this.$route.params.stockId}
          const vm = this;
          fetchStock(
            params,
            function(response) { //on successful data retrieval
              self.stock = response.data.payload // payload = {'name': test123}
              console.log(response)
            },
            function(responseError) { //on error
              console.log(responseError)
            }
          )
        }
    

    我建议在vm 声明中使用const 而不是var,以明确vm 的值是一个常量。

    【讨论】: