组件重新渲染

630 阅读1分钟

vue是数据驱动的,数据更新进而使组件得以重新渲染,有时候也会碰到数据改变了组件没有重新渲染。vue对某个属性或变量变化做出响应,即使所有依赖项实际上都没有改变。

v-if

指令仅在组件为true时才会渲染,false在DOM中不存在

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

forceUpdate方法

vue 会通过更新视图来响应依赖项的更改,当调用forceUpdate时,也可以强制更新 this.$forceUpdata();

添加key(最优方法,推荐方法)

让组件重新渲染的方法:给组件绑定key值,更改key绑定的值就可以重新渲染组件。 官网说明:当key 值变更时,会自动的重新渲染。如果key发生更改,Vue 就会知道应该删除旧组件并创建新组件。

<template>
  <component-to-re-render :key="componentKey" />
</template>
export default {
  data() {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender() {
      this.componentKey += 1;  
    }
  }
}