如何重新安装组件?

WoJ*_*WoJ 16 vue.js vue-component vuejs2

我有一个组件作为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>
Run Code Online (Sandbox Code Playgroud)

<my-component>功能(它显示一些表单输入)和$emit数据到父.

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

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

我的理解是一个组件是在渲染过程中在dom中正确注入的HTML/CSS/JS代码,因此我担心"重新安装"它的概念不存在 - 我只是想在去之前确保data() - 重写方式.

Dan*_*iel 40

我不得不使用一个表组件来做到这一点,该组件没有考虑包含更改数据的方法.诀窍是改变密钥.当密钥更改时,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
  }
})
Run Code Online (Sandbox Code Playgroud)
<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++">press this button to reload the component</button>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 你能问一个单独的问题吗? (4认同)
  • 谢谢 - 这太棒了。这也完全符合我的预期用途,我需要为组件提供一些 id(作为道具传递)。我在这里和那里阅读了有关组件中的“key”的信息,这是一个了解更多信息的机会。再次感谢! (3认同)
  • 这不会重新安装它。它只会重新渲染视图。 (3认同)

小智 13

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

<template>
  <my-component v-if="renderComponent" />
</template>
Run Code Online (Sandbox Code Playgroud)

在您的脚本中,您将添加使用 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>
Run Code Online (Sandbox Code Playgroud)

这是这里发生的事情:

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