求助:使用Axios请求API后无法通过Vue的v-for渲染列表
问题分析与解决方案
嘿,我一眼就瞅出问题所在啦!核心bug是axios回调里的this指向不对——你在then的普通function回调里给this.movies赋值,但这里的this根本不是Vue实例,所以Vue的movies数组完全没被更新,v-for自然渲染不出半条数据。
下面给你三种靠谱的解决办法,选一个顺手的用就行:
方法1:用箭头函数(最推荐)
箭头函数不会绑定自己的this,会直接继承外层作用域的this(也就是咱们的Vue实例),改起来超简单:
var vm = new Vue({ el: '#app', data: { movies: [] }, created() { this.getMovie(); }, methods: { getMovie: function () { axios.get("https://api.douban.com/v2/movie/top250") // 把普通function换成箭头函数就行 .then((res) => { console.log(res.data.subjects); this.movies = res.data.subjects; }) .catch(function (error) { console.log(error); }); } } })
方法2:提前存好Vue实例的this
在getMovie方法开头,把当前Vue实例的this存成一个变量,后续回调里用这个变量操作:
var vm = new Vue({ el: '#app', data: { movies: [] }, created() { this.getMovie(); }, methods: { getMovie: function () { // 先把Vue实例的this存起来 const self = this; axios.get("https://api.douban.com/v2/movie/top250") .then(function (res) { console.log(res.data.subjects); // 用self代替this赋值 self.movies = res.data.subjects; }) .catch(function (error) { console.log(error); }); } } })
方法3:用bind绑定this
给then的回调函数手动绑定Vue实例的this:
var vm = new Vue({ el: '#app', data: { movies: [] }, created() { this.getMovie(); }, methods: { getMovie: function () { axios.get("https://api.douban.com/v2/movie/top250") // 用bind把this绑定到Vue实例上 .then(function (res) { console.log(res.data.subjects); this.movies = res.data.subjects; }.bind(this)) .catch(function (error) { console.log(error); }); } } })
你的HTML代码完全没问题,只要把JS里的this指向修复好,v-for就能正常遍历movies数组渲染出电影列表啦!
内容的提问来源于stack exchange,提问作者wen tian
相关产品推荐
相关产品推荐

