解决Vue数组更新不渲染的问题

当使用索引直接赋值和直接修改数组长度时,Vue不能检测出变动的数组。
这样写页面显示的是共0个

<span class="pull-right">已全部加载,共{{fileDatas.length}} 个</span>

js:

export default {
    data() {
        return {
          fileDatas: []
        }
    },
    created() {
        this.getData();
     },
     methods: {
       getData() {
            var that = this
            var api ='/api/directory/null';
            console.log('api:' + api)
            that.$axios.get(api).then((res) => {
                console.log('data' + JSON.stringify(res.data.data))
                var i =0
                for (i=0;i<res.data.data[0].children.length;i++){
                    that.fileDatas[i] = res.data.data[0].children[i]
                }
                console.log('that.fileDatas##' + that.fileDatas.length)
                console.log('that.fileDatas = ' + JSON.stringify(that.fileDatas))
            })
        }
     }

getData方法要改成下面的,给数组赋值要写成this.$set(),出现的结果是正确的。

 methods: {
       getData() {
            var that = this
            var api ='/api/directory/null';
            console.log('api:' + api)
            that.$axios.get(api).then((res) => {
                console.log('data' + JSON.stringify(res.data.data))
                var i =0
                for (i=0;i<res.data.data[0].children.length;i++){   
                    this.$set(this.fileDatas,i,res.data.data[0].children[i])
                    console.log('this.fileDates+++' + JSON.stringify(this.fileDatas))
                }
                console.log('that.fileDatas##' + that.fileDatas.length)
            })
        },
     }

如果是对象数组可以在for循环中定义一个对象赋给数组

 for (i=0;i<res.data.data[0].children.length;i++){
                    var obj = new Object()
                    obj.id = res.data.data[0].children[i].id
                    obj.name = res.data.data[0].children[i].name
                    obj.size = res.data.data[0].children[i].size
                    obj.checked = false
                    obj.iconStyle = 'fa fa-folder slot-t-top-button'
                    obj.createTime = res.data.data[0].children[i].createTime
                    console.log('obj===' + JSON.stringify(obj))
                    this.$set(this.fileDatas,i,obj)
                    console.log('this.fileDates+++' + JSON.stringify(this.fileDatas))
                }

作为笔记使用,借鉴 https://www.jb51.net/article/126756.htm
关于vue set 的使用可以借鉴 https://blog.youkuaiyun.com/qq_30455841/article/details/78666571

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值