Vue.js中数组值变化时如何渲染或更新列表?附实现代码
在Vue.js中数组值变化后更新列表的问题解决
先看你的代码,目前数组更新后没触发列表渲染,主要有两个核心问题需要修正:
1. 回调函数中的this指向错误
在axios的then回调里,普通函数的this并不指向Vue实例,所以你给this.loctionsResults赋值的操作根本没修改到Vue data里的变量,自然不会触发视图更新。
2. 变量拼写错误
你data里的变量写成了loctionsResults,少了一个字母c,正确应该是locationsResults,这个拼写错误也会导致赋值无效。
修正方案
这里提供几种解决this指向问题的实用方法:
方法一:使用箭头函数(最推荐)
箭头函数会自动继承外层作用域的this,也就是Vue实例,写法最简洁:
const app = new Vue({ el:'#app', data:{ searchedLocation:'', locationsResults:[] // 修正拼写错误 }, watch:{ searchedLocation:function(){ this.getLocations(); } }, methods:{ getLocations: _.debounce(function(){ axios.get('/getLocations/'+ this.searchedLocation) .then((response) => { // 改成箭头函数 this.locationsResults = response.data; console.log(this.locationsResults); }) .catch(function (error) { console.log(error); }); },500) } })
方法二:提前保存this到变量
在axios请求前把Vue实例的this存成一个变量,比如self,在回调里用这个变量操作:
const app = new Vue({ el:'#app', data:{ searchedLocation:'', locationsResults:[] }, watch:{ searchedLocation:function(){ this.getLocations(); } }, methods:{ getLocations: _.debounce(function(){ const self = this; // 保存Vue实例的this axios.get('/getLocations/'+ this.searchedLocation) .then(function (response) { self.locationsResults = response.data; console.log(self.locationsResults); }) .catch(function (error) { console.log(error); }); },500) } })
方法三:用bind绑定this
给then的回调函数手动绑定Vue实例的this:
const app = new Vue({ el:'#app', data:{ searchedLocation:'', locationsResults:[] }, watch:{ searchedLocation:function(){ this.getLocations(); } }, methods:{ getLocations: _.debounce(function(){ axios.get('/getLocations/'+ this.searchedLocation) .then(function (response) { this.locationsResults = response.data; console.log(this.locationsResults); }.bind(this)) // 绑定this到Vue实例 .catch(function (error) { console.log(error); }); },500) } })
额外提示:Vue数组更新检测规则
Vue能自动检测到数组的这些方法调用并触发视图更新:
push()、pop()、shift()、unshift()、splice()、sort()、reverse()
如果是直接修改数组索引(比如this.locationsResults[0] = newVal)或者修改数组长度,Vue无法检测到,这时候需要用Vue.set(this.locationsResults, index, newVal),或者像你代码里那样直接重新赋值整个数组(这种操作是可以被Vue检测到的,前提是this指向正确)。
内容的提问来源于stack exchange,提问作者Rakesh Kohali
相关产品推荐
相关产品推荐

