blog icon indicating copy to clipboard operation
blog copied to clipboard

强制组件重新渲染

Open huangshuwei opened this issue 6 years ago • 0 comments

前言

最近在用element ui做一个后台系统,发现当菜单数据变更后,菜单显示异常的问题,通过 vue 的devtool 发现,element ui 的菜单组件并没有很好的处理数据变化的渲染重置问题,比如默认菜单属性值变更后并不生效,当然还有其他的问题。

方案一

我想到的方案是当菜单数据变更后,通过watch 监听,先去销毁当前的菜单组件,然后再重现渲染。使用 v-if 可以解决这个问题

<template>
   <third-comp v-if="reFresh"/>
</template>

<script>
   export default{
       data(){
          return {
                reFresh:true,
                menuTree:[]
            }
       },
       watch:{
             menuTree(){

                  this.reFresh= false
                  this.$nextTick(()=>{
                    
                    this.reFresh = true
                })
            }
       }
}
</script>

这种方式虽然可以实现,太不优雅

方案二

通过vue key 实现,原理官方文档。所以当key 值变更时,会自动的重新渲染。

<template>
   <third-comp :key="menuKey"/>
</template>

<script>
   export default{
       data(){
          return {
                menuKey:1
            }
       },
       watch:{
             menuTree(){

                ++this.menuKey
            }
       }
}
</script>

完...

huangshuwei avatar Nov 03 '18 15:11 huangshuwei