【问题标题】:create dynamic components VUE创建动态组件 VUE
【发布时间】:2020-02-29 02:55:08
【问题描述】:

我对如何创建动态组件有疑问,而不是通过标签<component :is=''>,如果不是,则该组件在DOM中不存在,并通过javascript插入。

如在 jquery 中添加 $("body").append("<div class="modal"></div>"),以添加新的模态

示例:https://jsfiddle.net/yu9oca2n/

代码:https://codesandbox.io/embed/vue-template-5cx5l?fontsize=14

jQuery

​​>

代码示例 JQuery

$("#button").click(function() {
  $("#modals").append("<div class='modal'>modal</div>");
});
<!doctype html>
<html>

<head></head>

<body>
  <div id="modals"></div>
  <hr>
  <button id="button">add input tag</button>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</body>

</html>

VUE

组件父级

<template>
  <div>
    <p>Hello</p>
    <hr>
    <a @click="insertModal">Insert Modal</a>
    <hr>

    <modal num="1"></modal>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {},
  methods: {
    insertModal() {
      /**
       * How to do so that when you enter here,
       * add one more modal, without putting this in a list,
       * because this modal can be called from anywhere on the web
       *
       * MODAL : <modal num="_x_" @clickEvent="eventClick"></modal>
       */
      // ??
    }
  },
  eventClick() {
    /** modal event click */
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

组件模态

<template>
  <div>MODAL {{num}}</div>
</template>

<script>
export default {
  name: "modal",
  props: ["num"],

  data: function() {
    return {};
  },

  methods: {}
};
</script>

【问题讨论】:

    标签: javascript vue.js dynamic components


    【解决方案1】:

    在组件数据中创建一个数组,并为数组中的每个项目显示一个模态

    <template>
      <div>
        <p>Hello</p>
        <hr>
        <a @click="insertModal">Insert Modal</a>
        <hr>
        <modal v-for="num in modals" :num="num" :key="num" @clickEvent="eventClick($event, num)"></modal>
    
        <modal num="1"></modal>
      </div>
    </template>
    
    <script>
    export default {
      name: "HelloWorld",
      props: {},
      data() {
         return {
           modals: [],
         };
      },
      methods: {
        insertModal() {
          this.modals.push(this.modals.length)
        }
      },
      eventClick($event, modalNumber) {
        /** modal event click */
      }
    };
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-22
      • 2019-07-12
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2019-12-24
      相关资源
      最近更新 更多