vue更新create()上的数据

问题描述 投票:0回答:1

我正在尝试从创建的hook()中的view data()中更新数组,但是控制台说allFish是未定义的。我对vue数据作用域还不太满意,我希望有人可以让我知道这是否是字典问题,或者从get请求接收数据时是否有更好的方法在create()上更新我的数据,然后将其添加到我的数据中的数组。

我当前的app.vue

export default {
  name: "App",
  components: {
    WebMap
  },
  data: () => ({
    coords: {
      latitude: -118,
      longitude: 34,
    },

    date: '',
    fishType: '',
    allFish: []

  }),

  created(){
    this.allFish = this.fetchFishLocations()
  },

  methods: {

    fetchFishLocations(){

         axios.get('http://localhost:3000/allFish')
            .then(function (response) {
              // handle success
              console.log(response.data.fish);
              return response.data.fish
            })
            .catch(function (error) {
              // handle error
              console.log(error);
            })

    },


    async updateCenter() {
      console.log(this.allFish)   //check to see if allFish is defined
      await this.getLocation();
      this.addFishToDb()
    },

  },
};
vue.js axios state
1个回答
0
投票

您需要在axios-> then方法中填充allFish。

...
created() {
  this.fetchFishLocations();
},
methods: {
    fetchFishLocations(){

         axios.get('http://localhost:3000/allFish')
            .then(function (response) {
              // handle success
              console.log(response.data.fish);
              this.allFish = response.data.fish;
            })
            .catch(function (error) {
              // handle error
              console.log(error);
            })

    },
}
...

0
投票

称为fetchFishLocations的函数只是返回未定义。您最好了解诺言的使用。顺便说一句,使用箭头功能更容易

// solution 1
created(){
    this.fetchFishLocations()
},
methods: {
    fetchFishLocations(){
         const that = this
         axios.get('http://localhost:3000/allFish')
            .then(function (response) {
              // handle success
              console.log(response.data.fish);
              that.allFish = response.data.fish
            })
            .catch(function (error) {
              // handle error
              console.log(error);
            })
    }
}

// solution 2
created(){
    const that = this
    this.fetchFishLocations()
        .then(function (response) {
              // handle success
              console.log(response.data.fish);
              that.allFish = response.data.fish
            })
        .catch(function (error) {
              // handle error
              console.log(error);
            })
},
methods: {
    fetchFishLocations(){
         return axios.get('http://localhost:3000/allFish')
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.