問題描述:我們在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()”是調用的后台的一個方法。