我正在尝试从创建的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()
},
},
};
您需要在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);
})
},
}
...
称为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')
}
}