34

我有一个作为 DOM 渲染的一部分安装的组件。应用程序的骨架是

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
  </head>
  <body>
    <div id="app">
      <my-component></my-component>
      <button>press this button to reload the component</button>
    </div>
  </body>
</html>

<my-component>是功能性的(它显示一些表单输入)和$emit父级的数据。

有没有办法重新安装它?目标是让组件内容和设置就像它是第一次渲染一样(包括重置data()保持其状态的元素)。

一些解决方案,但他们都假设重写data(),我想避免。

我的理解是,一个组件实际上是在渲染过程中在正确位置注入到 dom 中的 HTML/CSS/JS 代码,所以我担心“重新安装”它的概念不存在 - 我只是想在去之前确保数据() - 重写方式。

4

2 回答 2

77

诀窍是改变密钥

当 key 发生变化时,vue 将其视为一个新组件,因此会卸载“旧”组件,并挂载一个“新”组件。

看例子,created()钩子只会运行一次,所以如果你看到值变化,你看到的是一个全新的对象。

例子:

Vue.component('my-component', {
  template: `<div>{{ rand }}</div>`,
  data() {
    return {
      rand: ''
    }
  },
  created() {
    this.rand = Math.round(Math.random() * 1000)
  }
});

new Vue({
  el: '#app',
  data: {
    componentKey:0
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.8/vue.min.js"></script>

<div id="app">
  <my-component :key="componentKey"></my-component>
  <button @click="componentKey=!componentKey">press this button to reload the component</button>
</div>

于 2017-11-24T04:53:53.567 回答
3

在您的模板中,您将添加 v-if 指令:

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

在您的脚本中,您将添加这个使用 nextTick 的方法:

<script>
  export default {
    data() {
      return {
        renderComponent: true,
      };
    },
    methods: {
      forceRerender() {
        // Remove my-component from the DOM
        this.renderComponent = false;

        this.$nextTick(() => {
          // Add the component back in
          this.renderComponent = true;
        });
      }
    }
  };
</script>

这就是这里发生的事情:

最初 renderComponent 设置为 true,因此渲染了 my-component 当我们调用 forceRerender 时,我们立即将 renderComponent 设置为 false 我们停止渲染 my-component 因为 v-if 指令现在评估为 false 在下一个滴答时 renderComponent 设置回 true 现在v-if 指令的计算结果为 true,因此我们再次开始渲染 my-component

于 2021-06-29T09:09:53.573 回答