这行得通,但我确信有更好的方法来做到这一点。请查看靠近底部的 document.getElementsByClassName()
部分。
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>
模态.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>
有更好的方法吗?
最佳答案
是的,它是从模态组件中发出关闭事件,而不是在收到关闭发出时处理父组件中的关闭。我不能相信,因为我在官方 vue 网站上看到了这个 here .
基本上在模态模板中
<button @click="$emit("close")">close </button>
然后在使用模态的组件中,在数据中添加开放模态属性
data: function () { return { open: false }}
当你使用模态组件时
<modal @close="open = false">...</modal>
请注意@close 是您从模态发出的事件,如果您在模态中使用 $emit ("die"),它可以是任何 @die 起作用的事件。
当你想打开模式时,你可以使用类似的方法
<a @click="open = true">open modal</a>
如果您这样做,它的数据驱动且易于重用。
编辑
好的,所以如果你想从模态组件外部添加按钮,那么定义你的插槽,只需在这些插槽之一或所有插槽中添加一个按钮,这将使 open = false
关于javascript - 在 Vue 中添加 "close modal"按钮的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42330304/