Vue this.$nextTick() 之后再执行,导致渲染不准确

问题

 this.$nextTick(()=> {
                this.$refs.multipleTable.toggleAllSelection()

                this.isChecked = false
            })

注意:
this.$refs.multipleTable.toggleAllSelection() 必须放在this.$nextTick() 里面执行才能生效

如上所示 我希望先执行 this.$refs.multipleTable.toggleAllSelection(),再this.isChecked = false,但是经过测试发现 this.isChecked = false 总是在前执行导致页面渲染不正确

弱鸡解决法

this.$nextTick(()=> {
                this.$refs.multipleTable.toggleAllSelection()

                setTimeout(() => {
                    this.isChecked = false
                }, 100);
                
            })

这样可以解决这个问题,但是总感觉不太好

  • 尝试过 封装 async awit 但是无效 如下:
const nextTickAsync = () => {
                return new Promise((resolve, reject) => {
                    this.$nextTick(() => {
                        this.$refs.multipleTable.toggleAllSelection();
                        resolve(true)
                    })
                })
            }

            const isCheckedAsycn = () => {
                return new Promise((resolve, reject) => {
                    this.$nextTick(() => {
                        this.isChecked = false
                        resolve(true)
                    })
                })
            }
            
            (async () => {
                await nextTickAsync()
                await isCheckedAsycn()
            })()

求问解决方法 ?

如何先执行完 this.$nextTick() 在执行后续的this.isChecked = false

阅读 6.7k
5 个回答
this.$refs.multipleTable.toggleAllSelection()
this.$nextTick(()=> {
    this.isChecked = false
})

注意:
this.$refs.multipleTable.toggleAllSelection() 必须放在this.$nextTick() 里面执行才能生效

    // element-ui 表格提供的toggleAllSelection 源码是这样的
    //  toggleAllSelection内部是异步 且没有返回promise 也就是说不可控 
     toggleAllSelection() {
        this.store.commit('toggleAllSelection');
     }
     
     // 这样是不合理的 但确实可行 应该从你的出发点去考虑有没有别的方式解决
     async yourMehtod() {
         await this.$nextTick()
         this.$refs.multipleTable.toggleAllSelection()
         // 等待toggleAllSelection触发的dom更新后再次执行
         await this.$nextTick()
         this.isChecked = false
     }
        

可以转换个思路试试。
this.$refs.multipleTable.toggleAllSelection() 这句代码如果造成了状态的改变。

尝试写个watch,在watch里面写 this._isChecked = false;

this.$nextTick(()=> {
    this.$refs.multipleTable.toggleAllSelection()
    this.$nextTick(()=> {
        this.isChecked = false
    })
})

再套一层$nextTick不就得了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题