簡體   English   中英

如何在 Vue.JS 中將現有組件添加到模板 onclick?

[英]How to add an existing component to a template onclick in Vue.JS?

我希望能夠通過單擊按鈕將組件添加到我的模板中。 讓我告訴你我有什么: Draggable.vue 是我想在單擊按鈕時添加的組件。

<template>
  <div ref="draggableContainer" id="draggable-container" @mousedown="dragMouseDown">
    <div id="draggable-header" >
      <slot name="header"></slot>
    </div>
    <slot name="main"></slot>
    <slot name="footer"></slot>
  </div>
</template>

<script>
export default {
  name: 'DraggableDiv',
  data: function () {
    return {
      positions: {
        clientX: undefined,
        clientY: undefined,
        movementX: 0,
        movementY: 0
      }
    }
  },
  methods: {
    dragMouseDown: function (event) {
      event.preventDefault()
      // get the mouse cursor position at startup:
      this.positions.clientX = event.clientX
      this.positions.clientY = event.clientY
      document.onmousemove = this.elementDrag
      document.onmouseup = this.closeDragElement
    },
    elementDrag: function (event) {
      event.preventDefault()
      this.positions.movementX = this.positions.clientX - event.clientX
      this.positions.movementY = this.positions.clientY - event.clientY
      this.positions.clientX = event.clientX
      this.positions.clientY = event.clientY
      // set the element's new position:
      this.$refs.draggableContainer.style.top = (this.$refs.draggableContainer.offsetTop - this.positions.movementY) + 'px'
      this.$refs.draggableContainer.style.left = (this.$refs.draggableContainer.offsetLeft - this.positions.movementX) + 'px'
    },
    closeDragElement () {
      document.onmouseup = null
      document.onmousemove = null
    }
  }
}
</script>

<style>
#draggable-container {
  position: absolute;
  z-index: 9;
  height: 240px;
  width: 152px;
  background-color: rgb(170, 104, 43);
}
#draggable-header {
  z-index: 10;
}
</style>

這是我的 App.vue:

<template>
<div id = 'dd'>
  <button @click="createDraggableDiv">Créer bloc</button>
  <DraggableDiv class="col-11">
    <template>

    </template>
  </DraggableDiv>
</div>


</template>

<script>
import DraggableDiv from './components/DraggableDiv.vue'


export default {
  name: 'App',
  components: {
    DraggableDiv,
  },
  methods:{
    createDraggableDiv(){
       //function to add the DraggableDiv component to my template
    }
  }

}
</script>

<style>


</style>

當我啟動它時,我的應用程序上已經有一個 DraggableDiv,但我希望能夠使用該按鈕添加更多內容。

我你有什么想法可以幫助我做到這一點,請告訴我! 謝謝!

您可以使用 v-for 指令實現此目的:

<template>
  <div>
    <your-component v-for="index in count" :key="index"></p>
    <button v-on:click="addComponent">Add</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        count: 1
      };
    },
    methods: {
      addComponent() {
        this.count += 1;
      }
    }
  };
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM