问题描述:我们在mounted内执行异步方法,会先执行后边的语句,这就导致取不到想要的值。
方法:我们在方法中加入回调函数,将mounted的同步语句放在回调函数内,渲染语句套上$nextTick。
示例:
data() { return { carouselArr:[], } }, methods: { getList(callback) { fun().then(res => { this.carouselArr = res.data; console.log(this.carouselArr); // 回调 callback(this.carouselArr); }) } }, mounted() { var _this = this; this.getList(function (arr) { _this.$nextTick(() => { console.log(arr); }); }); }
示例中出现的“fun()”是调用的后台的一个方法。