head-img Force's Blog

Vue使用Array.prototype.push.apply导致视图不刷新问题解决

JavaScript

vue移动端列表项目中使用searchFormData作为列表对象,追加数据使用Array.prototype.push.apply
接口返回数据后视图不刷新,查阅资料后是因为vue数组更新检测包含一组观察数组的变异方法,所以它们也将会触发视图更新。这些方法如下:

push()
pop()
shift()
unshift()
splice()
sort()
reverse()

由于searchFormData是对象并且使用了vue监测不到的Array.prototype.push.apply,所以使用视图强制更新来解决,在使用Array.prototype.push.apply(this.searchFormData, res.body.data.data);后增加this.$forceUpdate();来强制刷新视图以解决问题。

export default {
    name: "xxx",
    data() {
        return {
            searchFormData: {},
        }
    },
    methods: {
        loadCareer(type, value) {
            let that = this;
            this.$http.post(
                process.env.SERVER_URL + '/api/xxx/search_career',
                data,
                {emulateJSON:true}
            ).then( function(res) {
                if(res.body.code === 1) {
                    if(res.body.data.data.length !== 0) {
                        //追加对象
                        Array.prototype.push.apply(this.searchFormData, res.body.data.data);
                        //强制更新
                        this.$forceUpdate();
                    }
                    that.loading = false;
                }else {
                    this.$notify({ type:'warning', message:'没有职位结果' });
                }
            });
        }
    }

}

虽然可以通过强制刷新来解决此问题, 还是推荐使用Object.assign来追加合并对象

     Object.assign(this.searchFormData, res.body.data.data);
点我评论
打赏本文
二维码


125

文章

14

标签

 访客统计  Update-******