1. 程式人生 > 其它 >vue this is undefined

vue this is undefined

技術標籤:vuejavahtmles6

在使用axios經常會出現這個問題

如下面程式碼

data(){
  return{
    goods:{
      title:null,
      subTitle:null,
      originalCost:null,
      currentPrice:null,
      discount:null,
      isFreeDelivery:null
    }
  }
},

  mounted:function()
  {//this is undefined
    axios.get("http://localhost:8081/get/goods/749").then(function (response){
      console.log(response);
      var _this = this;
      _this.goods = response.data;
    });

修改後:只需要將function換成=> 箭頭函式就可以了

mounted:function()
  {
    axios.get("http://localhost:8081/get/goods/749").then((response)=>{
      console.log(response);
      var _this = this;
      _this.goods = response.data;
    });