如何在 VueJS 中重新挂载组件? [英] How to re-mount a component in VueJS?

查看:136
本文介绍了如何在 VueJS 中重新挂载组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<头><meta charset="UTF-8"><title>title</title><身体><div id="应用程序"><我的组件></我的组件><button>按下这个按钮重新加载组件</button>

</html>

是功能性的(它显示一些表单输入)和 $emit 数据到父级.

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

一些解决方案,但它们都假设重写了data(),这是我想避免的.

我的理解是,组件实际上是在渲染过程中将 HTML/CSS/JS 代码注入到 dom 中的正确位置,因此我担心重新安装"它的概念不存在 - 我只是想做在使用 data()-rewrite 方式之前确定.

解决方案

诀窍是改变密钥

当key发生变化时,vue将其视为一个新组件,因此会卸载旧"组件,并安装一个新"组件.

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

示例:

Vue.component('my-component', {模板:`<div>{{rand }}</div>`,数据() {返回 {兰特:''}},创建(){this.rand = Math.round(Math.random() * 1000)}});新的 Vue({el: '#app',数据: {组件密钥:0}})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.8/vue.min.js"></script><div id="应用程序"><my-component :key="componentKey"></my-component><button @click="componentKey=!componentKey">按下这个按钮重新加载组件</button>

I have a component which is mounted as part of the DOM rendering. The skeleton of the application is

<!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> is functional (it displays a few form inputs) and $emit data to the parent.

Is there a way to re-mount it? The goal is to have a component content and setup as if it was just rendered for the first time (including a reset of the data() elements which hold its state).

There are some solutions to that but they all assume a rewrite of data(), which I would like to avoid.

My understanding is that a component is actuall HTML/CSS/JS code injected in the dom in the right place during the rendering so I fear that the concept of "re-mounting" it does not exist - I just wanted to make sure before going the data()-rewrite way.

解决方案

The trick is to alter the key

When the key changes, vue regards it as a new component, so it will unmount the "old" component, and mount a "new" component.

See example, the created() hook will only run once, so if you see the value change, you're seeing a brand new object.

example:

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>

这篇关于如何在 VueJS 中重新挂载组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆