如何在VueJS中重新挂载组件?

2024-03-10

我有一个作为 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()保持其状态的元素)。

一些解决方案 https://github.com/vuejs/vue/issues/702但他们都假设重写data(),我想避免这种情况。

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


诀窍是改变密钥

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

参见示例,created()hook 只会运行一次,因此如果您看到值发生变化,您就会看到一个全新的对象。

example:

Vue.component('my-component', {
  template: `<div>{{ rand }}</div>`,
  data() {
    return {
      remount: true
    }
  },
  created() {
    this.remount = !this.remount; // true▶false▶true▶false...
  }
});

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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在VueJS中重新挂载组件? 的相关文章

随机推荐