1、为什么要手动刷新组件

        有的时候出于“某种因素”,vue的响应式机制不能够将数据及时反映到组件上,我们认为Vue会对某个属性或变量的变化做出响应,但实际上并不是这样。在某些情况下,Vue的响应系统根本检测不到任何变化,所以需要我们手动去刷新组件。

2、手动刷新组件的方法

(1)简单粗暴:刷新页面

非常不妥,用户体验非常糟糕,never be used!!!!!!!!!!!

(2)使用v-if

<template>
  <my-component v-if="renderComponent" />
</template>
<script>
  export default {
    data() {
      return {
        renderComponent: true,
      };
    },
    methods: {
      forceRerender() {
        // 从 DOM 中删除 my-component 组件
        this.renderComponent = false;
        
        this.$nextTick(() => {
          // 在 DOM 中添加 my-component 组件
          this.renderComponent = true;
        });
      }
    }
  };
</script>

存在两个问题 

a. 如果没有等到next tick,那么就无法对renderComponent 进行更新

b. 第二次渲染时,销毁旧的组件,创建一个新的组件,那么所有的生命周期的事件都必须要尽力,created,monted等。

(3)使用forceUpdate方法

 

(4)

 

3、总结

Logo

前往低代码交流专区

更多推荐