简体   繁体   English

VUE - 为什么不在 VUE 中创建这个 DOM 元素?

[英]VUE - Why isn't this DOM element being created in VUE?

Question: The following script creates a div, and is supposed to be append to another div.问题:以下脚本创建了一个 div,并且应该是 append 到另一个 div。 I am trying to implement vanilla javascript within this component.我正在尝试在此组件中实现 vanilla javascript。 How can I create this DOM element?如何创建这个 DOM 元素?

Here is the component:这是组件:

<template>
<div class="backdrop" @click="closeModal">
    <div class="modal">
        <div id="elementContainer">{{ createDiv }}</div>
    </div>
</div>
<script>
    export default {

    props: [ 'elementSummary', 'elementName', 'elementSymbol', 'elementNumber', 'elementPhase', 
'elementShell', 'elementDensity' ],
    methods: {
     createDiv(){
        
        const newDiv = document.createElement('div')
        let divContainer = document.getElementById("elementContainer").appenedChild(newDiv)

  }
}

It doesn't work because you are trying to interpolate a function definition.它不起作用,因为您正在尝试插入 function 定义。

If you want to append a new div on click, create a localized state in your modal component.如果您想在点击时 append 一个新的 div,请在您的modal组件中创建一个本地化的 state。 Toggle that state on click and use v-if directive to append that div dynamically在点击时切换 state 并使用v-if指令到 append 动态 div

   export default {
      // vue component state
      data: function () { 
       return {
         showContent: false // we'll use this to show/hide the dynamic div
       }
      }, 

      props: [],

      methods: {
        /**
        * update state on click
        **/
        createDiv(){
         this.showContent = !this.showContent;
        }
      }
    }

In your template在您的模板中

 <template>
  <div class="backdrop" @click="closeModal">
    <div class="modal">
      <div id="elementContainer">
        <div v-if="showContent>
           ...
        </div>
      </div>
    </div>
  </div>
 </template>

When showContent value is changed, vue will accordingly remove or append the subtree in which it attached with a v-if attribute.showContent值更改时, vue将相应地删除或 append 附加了v-if属性的子树。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM