2017-02-19 11 views
1

這可以起作用,但我確信有更好的方法來做到這一點。請看底部附近的document.getElementsByClassName()部分。在Vue中添加「關閉模式」按鈕的更好的方法

HTML:

<modal> 
    <a slot="trigger">Show Modal</a> 
    <h3 slot="header">My Heading</h3> 
    <p slot="body">Here is the body of the modal.</p> 
    <div slot="footer"> 
    Here is the footer, with a button to close the modal. 
    <button class="close-modal">Close Modal</button> 
    </div> 
</modal> 

Modal.vue:

<template> 
    <span> 
     <span @click="show = true"> 
     <slot name="trigger"></slot> 
     </span> 
     <slot name="header"></slot> 
     <slot name="body"></slot> 
     <slot name="footer"></slot> 
    </span> 
</template> 

<script> 
    export default { 
     data() { 
      return { show: false } 
     }, 
     mounted(that = this) { 
      document.getElementsByClassName('close-modal')[0].addEventListener('click', function() { 
      that.show = false; 
      }) 
     } 
    } 
</script> 

有沒有更好的方式來做到這一點?

回答

1

是的,它是從模態組件中發出關閉事件,並且在接收到關閉發射時處理父組件中的關閉。我無法相信,因爲我在官方網站here上看到了這一點。

基本上在模式模板

<button @click="$emit("close")">close </button> 

然後在組件在您使用模式中的數據添加開放模式屬性

data: function() { return { open: false }} 

而當你使用模態分量

<modal @close="open = false">...</modal> 

心靈@close是你從modal發出的事件,它可以是任何@die在你使用$ emit(「die」)模態。

而當你想打開模式如果你這樣做了數據驅動的,易於重用,你可以使用類似的方法

<a @click="open = true">open modal</a> 

編輯

好了,所以,如果你想從模態分量之外添加按鈕然後定義你的插槽,就在這些插槽中的一個或全部添加一個按鈕,這將使open = false

+0

我想要將置於標記內,而不是在組件內部。這樣我可以用很多不同的方式關閉一個模態,但是隻有一個模態組件。 – Travis

+0

那麼它更容易,但你必須遵循相同的方法......我會加入到我的回答 – peaceman

+0

@peaceman,也許你可以幫助我:https://stackoverflow.com/questions/45451971/how-can- I-顯示模態式模態上-VUE組分 –