javascript - 在 Vue 中添加 "close modal"按钮的更好方法

标签 javascript vue.js

这行得通,但我确信有更好的方法来做到这一点。请查看靠近底部的 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/

相关文章:

javascript - 无法将ES6模块导入Vue单文件组件

vue.js - Vuex 在异步操作完成之前访问状态

javascript - 如何将 CSS 文件从源文件夹捆绑并复制到 dist 文件夹?

javascript - html 中的列表是否从父列表继承 id?

javascript - 资源解释为脚本,但在注入(inject) angular-route.map 时以 MIME 类型 text/html 传输

javascript - 这是使用 jQuery 解析 XML 时的错误吗?

asp.net - 如何获取RadioButtonList的innerText

javascript - Vue.js 基于子域加载 CSS

vue.js - 如何在 bootstrap-vue 中为 b-form-checkbox-group 设置所需的验证?

javascript - 注销后调用 Firebase getRedirectResult