vue-axios使用记录
问题
本人在Ajax
方面纯小白,所以在使用axios
时犯了个很简单的错误
我想通过API返回数据后接着执行父组件的一个函数
一开始的代码
<script>
import axios from 'axios'
export default {
data() {
return {
list: '',
length: '',
};
},
methods: {
getList(){
axios
.get('api_url')
.then(response => (
this.list = response.data['list'],
this.length = response.data['length'],
)
)
this.$emit('next_fuc', this.list, this.length),
},
}
};
</script>
结果就是明明接收到了数据,传给next_fuc
函数的值却是空值
解决
这是因为Ajax
是异步操作,还没有等返回数据就已经执行了this.$emit('next_fuc', this.list, this.length)
把需要等待数据返回的操作放在.then
里就可以解决
<script>
import axios from 'axios'
export default {
data() {
return {
list: '',
length: '',
};
},
methods: {
getList(){
axios
.get('api_url')
.then(response => (
this.list = response.data['list'],
this.length = response.data['length'],
this.$emit('next_fuc', this.list, this。length),
)
)
},
}
};
</script>