【问题标题】:Vue axios promise scope is not binding to current componentVue axios 承诺范围未绑定到当前组件
【发布时间】:2017-06-04 21:26:12
【问题描述】:

如何在方法对象中绑定函数。我相信如果我使用箭头功能,它应该自动与当前对象绑定。但是,它有自己的范围。因此,我无法在 http get 请求后更新数据变量。

这是我的客户组件。

 import axios from 'axios';

  export default {
    data () {
      return {
        customers: 'temp ',
        loading: 'false',
        error: null,
      }
    },
    created () {
      console.log(this)//this is fine 
      this.getCustomerList()
    },
    watch: {
      '$route': 'getCustomerList'
    },

    methods: {
      getCustomerList: () => {
        console.log(this)
        axios.get('/api/customers')
        .then((res)=>{
          if(res.status === 200){
          }
        })
      }
    }
  }

这是 console.log(this) 的结果..

这是我的 app.js 文件

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

import Customers from './components/Customers/Customers.vue'

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  history: true,
  routes: [
    { path: '/customers', component: Customers }
  ]
})

new Vue ({
  router
}).$mount('#app')

【问题讨论】:

    标签: vue.js axios


    【解决方案1】:

    尝试以下操作:

    methods: {
      getCustomerList () {
        console.log(this)
        var that = this
        axios.get('/api/customers')
        .then((res)=>{
          if(res.status === 200){
              //use that here instead of this
          }
        })
      }
    }
    

    【讨论】:

    • 这已经在错误的范围内,没有绑定到组件范围。
    • @user3882878 做了一些改动,它在我的代码中是这样工作的。
    • hmm.. 我不应该使用箭头功能。谢谢我刚刚意识到
    • 我尝试使用 function() {..} 声明方法,使用箭头函数,我尝试将箭头函数和 function() {...} 传递给 then 方法。我试过 var that = 这个技巧。它都不起作用。在 then 处理程序方法中,“this”不在范围内,该函数也无法看到词法范围内的变量(如“that”变量)。我正在使用的 axios (0.15.3) 和 vue (2.2.1) 和 vueify (9.4.0) 版本可能存在兼容性问题?
    • @DouglasA.Seifert 它应该有效,您能否添加相关代码并将其发布在问题中,以便对其发表评论。
    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多