Vue中重新渲染组件的方法总结

本文总结了Vue中重新渲染组件的几种常见方法,包括:避免全页刷新、使用v-if指令、forceUpdate方法和通过key属性。重点讲解了forceUpdate的使用、组件销毁与重建以及key的巧妙运用,帮助开发者高效解决组件更新问题。

Vue中重新渲染组件的方法总结

有时Vue的反应性系统还不够,您只需要重新渲染组件即可。
重新渲染组件有以下几个办法:

  • 可怕的方法:重新加载整个页面
  • 可怕的方法:使用v-if
  • 更好的方法:使用Vue的内置forceUpdate方法
  • 最好的方法:在组件上进行key更改

重新加载整个页面

非常不建议这样做,我们来看下一个办法

v-if指令,该指令仅在组件为true时才渲染。 如果为false,则该组件在DOM中不存在。
下面我们设置它以使其v-if能够正常工作的方式。

在您的template,您将添加v-if指令:

<template>
  <my-component v-if="renderComponent" />
</template>

script您将添加使用以下方法nextTick

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

这里发生的事情:

  • 最初renderComponent设置为true,因此my-component组件渲染
  • forceRerender中我们立即设置renderComponentfalse
  • 停止渲染组件my-component,因为该v-if指令现在的值为false
  • nextTick中将renderComponent上设置回true
  • 现在该v-if结果为true,因此我们my-component再次开始渲染

我们必须等到nextTick,否则我们不会看到任何变化。

在Vue中,一个 nextTick 是一个DOM更新周期。Vue将收集在同一 nextTick 中进行的所有更新,在 nextTick 结束时,它将根据这些更新来渲染 DOM 中的内容。如果我们不等到nextTick,我们对renderComponent的更新就会自动取消,什么也不会改变。

其次,当我们第二次渲染时,Vue将创建一个全新的组件。 Vue 将销毁第一个,并创建一个新的,这意味着我们的新my-component将像正常情况一样经历其所有生命周期-created,mounted等。

不过,这并不是一个很好的解决方案,往下看

使用forceUpdate

方法解读:

Vue中,$forceUpdate()的使用

方文档中指出,$forceUpdate具有强制刷新的作用。那在vue框架中,如果data中有一个变量:age,修改他,页面会自动更新。但如果data中的变量为数组或对象,我们直接去给某个对象或数组添加属性,页面是识别不到的<template>

  <p>{{userInfo.name}}</p>
  <button @click="updateName">修改userInfo</button>
</template>
<script>
  data(){
    return{
      userInfo:{name:'小明'}
    }
  },
  methods:{
    updateName(){
      this.userInfo.name='小红'
    }
  }
</script>

在updateName函数中,我们尝试给userInfo对象修改值,发现页面其实并没有变化

那这时候有两种解决方法:

方法一:

methods:{
  updateName(){
    this.userInfo.name='小红'//在此时,确实已经将userInfo对象修改完成
    console.log(this.userInfo.name);//输出结果: 小红
    this.$forceUpdate();//在这里,强制刷新之后,页面的结果变为'小红'
  }
}

$forceUpdate() 这个方法也可以处理 修改for循环 里面 item的属性值,没有渲染出来添加这个方法也生效

方法二:

methods:{
  updateName(){
    this.$set('userInfo',name,'小红');
  }
}

这是解决此问题的两种最佳方法之一,此方法得到Vue的官方支持。

下面是示例:

forceUpdate在组件实例本身以及全局实例上,可以通过两种不同的方式调用

// 全局
import Vue from 'vue';
Vue.forceUpdate();

// 使用组件实例
export default {
  methods: {
    methodThatForcesUpdate() {
      // ...
      this.$forceUpdate();
      // ...
    }
  }
}

重要提示:这不会更新您拥有的任何计算属性。调用forceUpdate只会强制重新渲染视图

最好的方法:修改组件的key达到组件重新渲染

在许多情况下,我们需要重新渲染组件。

要正确地做到这一点,我们将提供一个key属性,以便 Vue 知道特定的组件与特定的数据片段相关联。如果key保持不变,则不会更改组件,但是如果key发生更改,Vue 就会知道应该删除旧组件并创建新组件。

我们可以采用这种将key分配给子组件的策略,但是每次想重新渲染组件时,只需更新该key即可。

<template>
  <component-to-re-render :key="componentKey" />
</template>


export default {
  data() {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender() {
      this.componentKey += 1;  
      //this.componentKey += new Date();
    }
  }
}

每次 forceRerender被调用时,我们的componentKey都会改变。当这种情况发生时,Vue将知道它必须销毁组件并创建一个新组件。我们得到的是一个子组件,它将重新初始化自身并“重置”其状态。

原文链接:Vue中重新渲染组件的方法总结_六糖雪梨的博客-CSDN博客_vue重新渲染生命周期

原文链接:Vue子组件重新渲染_small xie的博客-CSDN博客

Vue 3 中,组件重新渲染机制主要依赖于响应式系统以及虚拟 DOM 的差异比较算法。以下是一些常见的触发组件重新渲染方法和机制: ### 1. 使用 `key` 属性控制组件重新渲染 这是推荐的方法之一,适用于 Vue 2 和 Vue 3。通过为组件绑定一个 `key` 属性,并在需要重新渲染时改变 `key` 的值,可以触发组件重新创建和渲染。这种方法利用了 Vue 的虚拟 DOM 算法,当 `key` 发生变化时,Vue 会认为这是一个新的组件实例,从而触发重新渲染。 ```vue <template> <div> <ChildComponent :key="refreshKey" /> <button @click="refreshChildComponent">刷新子组件</button> </div> </template> <script> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const refreshKey = ref(0); const refreshChildComponent = () => { refreshKey.value += 1; }; return { refreshKey, refreshChildComponent }; } }; </script> ``` ### 2. 使用 `v-if` 指令控制组件渲染状态 `v-if` 指令可以根据条件判断是否渲染组件。当条件为 `false` 时,组件会被销毁;当条件再次为 `true` 时,组件会被重新创建并渲染。这种方式适用于需要根据条件动态控制组件是否显示的场景。 ```vue <template> <div> <ChildComponent v-if="shouldRender" /> <button @click="toggleComponent">切换组件</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { shouldRender: true }; }, methods: { toggleComponent() { this.shouldRender = !this.shouldRender; } } }; </script> ``` ### 3. 使用 `vm.$forceUpdate()` 强制更新组件 `vm.$forceUpdate()` 是 Vue 提供的一个方法,用于强制更新组件。这种方法会跳过 Vue 的响应式更新机制,直接触发组件重新渲染。需要注意的是,`$forceUpdate()` 应该谨慎使用,因为它可能会导致性能问题。 ```vue <template> <div> <ChildComponent ref="childComponent" /> <button @click="forceUpdateComponent">强制更新组件</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { forceUpdateComponent() { this.$refs.childComponent.$forceUpdate(); } } }; </script> ``` ### 4. 使用响应式数据触发更新 在 Vue 3 中,响应式数据的变化会自动触发组件重新渲染。通过使用 `ref` 或 `reactive` 创建响应式数据,并在模板中使用这些数据,当数据发生变化时,组件会自动更新。 ```vue <template> <div> <p>{{ message }}</p> <button @click="updateMessage">更新消息</button> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const message = ref('初始消息'); const updateMessage = () => { message.value = '更新后的消息'; }; return { message, updateMessage }; } }; </script> ``` ### 5. 使用 `watch` 监听数据变化并手动触发更新 通过 `watch` 监听某些数据的变化,并在数据变化时手动触发组件的更新逻辑。这种方法适用于需要在数据变化时执行复杂操作的场景。 ```vue <template> <div> <p>{{ count }}</p> <button @click="incrementCount">增加计数</button> </div> </template> <script> import { ref, watch } from 'vue'; export default { setup() { const count = ref(0); const incrementCount = () => { count.value += 1; }; watch(count, (newVal, oldVal) => { console.log(`计数从 ${oldVal} 更新到 ${newVal}`); // 执行其他操作 }); return { count, incrementCount }; } }; </script> ``` ### 6. 使用 `provide/inject` 实现跨层级组件更新 在复杂的组件树中,可以通过 `provide` 和 `inject` 实现跨层级组件的数据共享和更新。父组件通过 `provide` 提供数据,子组件通过 `inject` 接收数据,当数据变化时,所有依赖该数据的组件都会重新渲染。 ```vue <!-- ParentComponent.vue --> <template> <div> <ChildComponent /> </div> </template> <script> import { provide, ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const theme = ref('dark'); provide('theme', theme); return {}; } }; </script> <!-- ChildComponent.vue --> <template> <div> <p>当前主题: {{ theme }}</p> </div> </template> <script> import { inject } from 'vue'; export default { setup() { const theme = inject('theme'); return { theme }; } }; </script> ``` ### 总结 在 Vue 3 中,有多种方法可以触发组件重新渲染,包括使用 `key` 属性、`v-if` 指令、`vm.$forceUpdate()` 方法、响应式数据的变化、`watch` 监听数据变化以及 `provide/inject` 实现跨层级组件更新。根据具体的业务需求和场景,可以选择合适的方法来实现组件重新渲染
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值