美文网首页
watch监听不到循环赋值的问题

watch监听不到循环赋值的问题

作者: 钢铁萝莉猫 | 来源:发表于2020-12-09 14:11 被阅读0次

情境:
watch监听ifprint的变化,为true的时候展示loading,并执行doToimg()方法。

      ifprint(val) {
            if (val) {
                console.log('loading')
                this.isLoading = true
                this.text = `正在准备预览... ${0} / ${this.myArray2.length}`
                this.doToimg()
            }
        },

doToimg()中给this.text循环赋值:

      doToimg() {
            this.myArray2 = this.myArray2.map((item, index, arr) => {
                this.text = `正在准备预览... ${index + 1} / ${arr.length}`
                ...//!! 执行一个含有promise+then的方法
                item.choosed = false
                return item
            })
        },

期间也监听this.text

        text: function (val) {
            console.log('watch', val) 
        }

循环结束后发现,在text的监听里,只监听到了最后一次循环,即打印:
loading
watch 正在准备预览... 10 / 10
原先预想的loading也没有按时显示,而是在promise.then后才显示。

修改一:

text放到computed里:

       text: {
            get() {
                return this.mytext
            },
            set(newval) {
                this.isLoading = true
                this.mytext = newval
                console.log('set ', newval)
            }
        }

doToimg() 外套一层settimeout,试图控制this.isLoading = truedoToimg()的执行顺序。

ifprint(val) {
            if (val) {
                console.log('loading')
                this.isLoading = true
                this.text = `正在准备预览... ${0} / ${this.myArray2.length}`
                setTimeout(() => {
                    this.doToimg()
                }, 0);
            }
        },

watch中的监听不变。
结果:loading依旧没有按时显示,但是在set()中监听到了text每一次的变化。
打印结果:

修改一打印结果.png

修改二:

把上面settimeout的时间设置为500
结果:表面看上去非常完美,loading竟然按时显示了!即在ifprinttrue的时候。
但我不清楚为什么,500是我瞎写的。

修改三:

先还原上述的修改。
doToimg()改为:

      doToimg() {
            this.myArray2 = this.myArray2.map((item, index, arr) => {
                setTimeout(() => {
                    this.text = `正在准备预览... ${index + 1} / ${arr.length}`
                    ...//!! 执行一个含有promise+then的方法
                }, 0)
                item.choosed = false
                return item
            })
        },

页面展示非常完美,loading也按时显示,text的每次变化也都能监听到!!
打印结果:

修改三打印结果.png

对此结果我还是表示非常不解,后来在网上发现了一篇帖子:
https://ask.csdn.net/questions/1092793
与我遇到的问题非常相似,请教了这位解答的大神后得到回答:


good good study , day day up

相关文章

网友评论

      本文标题:watch监听不到循环赋值的问题

      本文链接:https://www.haomeiwen.com/subject/qkdhgktx.html