【问题标题】:Bootstrap Modal Hide from VUE methodBootstrap Modal Hide from VUE 方法
【发布时间】:2019-10-04 06:30:47
【问题描述】:

我有一个 vuejs 组件,它显示一个模态对话框,里面有一个小表单。提交表单后,我想隐藏 Modal 但不知道该怎么做。提交时,表单调用父级中的方法。

这是组件代码

<template>
  <div>
    <div id="todoModal" class="modal fade" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">{{ title }}</h4>
            <button type="button" class="close" data-dismiss="modal">
              &times;
            </button>
          </div>
          <div class="modal-body">
            <form id="todoForm" @submit.prevent="$emit('save')">
              <div class="form-group">
                <label for="name">Todo name</label>
                <input
                  id="name"
                  v-model="todo.name"
                  type="text"
                  class="form-control"
                  aria-describedby="nameHelp"
                  placeholder="Enter Todo Name"
                />
                <small id="nameHelp" class="form-text text-muted"
                  >Enter your todo's name</small
                >
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button class="btn btn-primary mr-4" type="submit" form="todoForm">
              <span v-if="mode == 'create'">Create</span>
              <span v-if="mode == 'update'">Update</span>
            </button>
            <button
              type="button"
              class="btn btn-danger mr-auto"
              data-dismiss="modal"
              @click="
                $parent.showModal = false;
                $parent.getTodos();
              "
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CreateTodo",
  props: ["mode", "title", "todo", "showModal"],
  ref: "createTodoModal",
  mounted() {
    if (this.mode == "create") {
      this.title = "Create Todo";
    }
  },
  methods: {}
};
</script>
<style scoped></style>

这是我的 APP.js 文件

<template>
  <div id="app" class="container mt-5">
    <router-view
      ref="createtodo"
      class="CreateTodo"
      name="a"
      :todo="todo"
      :title="title"
      :mode="mode"
      :show-modal="showModal"
      @save="saveTodo"
    ></router-view>
  </div>
</template>

<script>
import { APIService } from "./APIServices";
const apiService = new APIService();

export default {
  name: "App",
  data: function() {
    return {
      mode: "create",
      title: "Create Todo",
      todo: {},
      todos: [],
      numberOfTodos: 0,
      showModal: false
    };
  },
  mounted: function() {
    this.getTodos();
  },

  methods: {
    saveTodo: function() {
      if (this.mode == "create") {
        apiService.createTodo(this.todo).then(
          result => {
            if (result.status === 200) {
              this.todo = result.data;
              this.getTodos();
            }
          },
          error => {}
        );
        this.showModal = false;
        // this.$refs.createtodo.$refs.todoModal
      } else if (this.mode == "update") {
        apiService.updateTodo(this.todo).then(
          result => {
            this.getTodos();
          },
          error => {}
        );
        this.showModal = false;
      } else if (this.mode == "update") {
        apiService.updateTodo(this.todo).then(
          result => {
            this.showModal = false;
            this.getTodos();
          },
          error => {}
        );
      }
    },
  }
};
</script>

<style lang="scss">
</style>

我尝试使用 ref 从 APP.js 引用 Modal,但它不起作用。

【问题讨论】:

  • 查看您的属性 "showModal" 它不用于显示/隐藏某些内容。没有引导 v-show 指令可能会有所帮助。
  • 它可以工作,但是当模态隐藏时,模态的深色背景不会消失。

标签: vue.js vuejs2 bootstrap-4


【解决方案1】:

为关闭 X 按钮添加一个 id"

<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="close">
   <span aria-hidden="true">&times;</span>
</button>

然后创建一个关闭modal的方法:

closeModal() {
   document.getElementById('close').click();
},

【讨论】:

    【解决方案2】:

    如果您使用的是 boostrap,则需要从中调用 hide an show 方法,因为 modal api 会动态创建 html 元素(作为深色背景)

    我建议创建一个保存方法而不是调用 $emit,您可以在发出保存信号之前调用模态隐藏方法。

    <script>
    import $ from 'jquery'
    
    export default {
      name: "CreateTodo",
      props: ["mode", "title", "todo"],
      ref: "createTodoModal",
      mounted() {
        if (this.mode == "create") {
          this.title = "Create Todo";
        }
      },
      methods: {
        save() {
           $('#ModalId').modal('hide')
           this.$emit('save')
        }
      }
    };
    </script>
    

    在这种情况下不需要showModal。

    【讨论】:

      【解决方案3】:

      就像@Dan Stoian 回复一样,你可以在 vue.js 中使用 ref :

      <button ref="Close" type="button" data-dismiss="modal" ...>
         ...
      </button>
      

      在你的处理程序中

      this.$refs.Close.click();
      

      【讨论】:

        【解决方案4】:

        你可以使用 v-if 来显示/隐藏模态

        在您的组件中:

          <div v-if="showModal">
            <div id="todoModal" class="modal fade" role="dialog">
            ...
            </div>
          </div>
        

        并将showModal 设置为 true/false 以分别显示/隐藏组件。

        【讨论】:

        • 嗨 Ittus.. 感谢您的建议。我试过了,它确实有效,但是当模态隐藏时,模态的背景并没有消失,
        • 如果您使用的是 Bootstrap,则需要使用 boostrap 方法隐藏/显示。
        【解决方案5】:

        你可以使用这个 npm 包

        npm i vue-js-modal
        

        https://www.npmjs.com/package/vue-js-modal

        你的代码应该这样修改:

        <template>
        <modal :name="'edit-modal'+id" height="auto">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Edit {{ mName }}</h5>
                <button type="button" class="close" @click="hideEditModal(id)">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="/user/update" method="patch" @submit.prevent="updateAssistant">
                <div class="modal-body">
                    <div class="position-relative form-group">
                        <label for="exampleAddress" class="">Full name</label><input name="name" v-model="editName" id="exampleAddress" placeholder="FullName" type="text" class="form-control">
                        <div v-if="errors.has('editName')" class="alert alert-danger">
                            {{ errors.first('editName') }}
                        </div>
                    </div>
        
                    <div class="position-relative form-group">
                        <label for="exampleEmail11" class="">Email</label><input name="email" v-model="editEmail" id="exampleEmail11" placeholder="email" type="email" class="form-control">
                        <div v-if="errors.has('editEmail')" class="alert alert-danger">
                            {{ errors.first('editEmail') }}
                        </div>
                    </div>
        
                    <div class="position-relative form-group">
                        <label for="examplePassword11" class="">Change Password</label><input name="password" v-model="editPassword" id="examplePassword11" placeholder="password" type="password" class="form-control">
                        <div v-if="errors.has('password')" class="alert alert-danger">
                            {{ errors.first('password') }}
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @click="hideEditModal(id)">Close</button>
                    <button type="submit" class="btn btn-primary">Save changes</button>
                </div>
                <span class="loader" v-if="this.loading" style="position: absolute; bottom: 0.515rem; left: 20px;">
                    <span class="ball-clip-rotate">
                        <div style=" border:1px solid #000;"></div>
                    </span>
                </span>
            </form>
        </modal>
        

        import Errors from '../../Errors.js'
        export default {
        
        name: 'AssistantEditModalComponent',
        
        props: [
            'mEmail',
            'mName',
            'id'
        ],
        
        data () {
            return {
                editPassword: null,
                disabled: false,
                errors: Errors,
                loading: false
            }
        },
        
        methods: {
            hideEditModal(id) {
                this.$modal.hide('edit-modal'+id);
            },
        
            setData() {
                this.editName = this.mName
                this.editEmail = this.mEmail
            },
        
            updateAssistant() {
                this.disabled = true;
                this.loading = true;
                const form = {
                    editName: this.mName,
                    editEmail: this.mEmail,
                    password: this.editPassword
                }
                axios.patch('/user/update/'+this.id, form)
                .then((response) => {
                    this.disabled = false
                    this.loading = false
                    this.hideEditModal(this.id)
                    this.alert(response)
                })
                .catch((err) => {
                    this.disabled = false
                    this.loading = false
                    Errors.fill(err.response.data.errors)
                })
            },
        
            alert(response) {
                swal(response.data.username, response.data.message, 'success')
            },
        },
        
        computed: {
            editName: {
                get: function() {
                    return this.mName
                },
                set: function(value) {
                    this.$emit('update:mName', value);
                }
            },
            editEmail: {
                get: function() {
                    return this.mEmail
                },
                set: function(value) {
                    this.$emit('update:mEmail', value);
                }
            }
        }}
        

        【讨论】:

          【解决方案6】:

          如果您不想添加任何额外的关闭按钮而不是模式标题的默认 X 按钮,您可以执行以下操作:

          <b-modal
              id="user-role"
              ref="role-modal"
              hide-footer
            >
          ...
          </b-modal>
          

          然后在你的方法中:

          hideModal() {
              this.$refs["role-modal"].$refs['close-button'].click()
          }
          

          【讨论】:

            猜你喜欢
            • 2018-07-17
            • 2012-11-06
            • 1970-01-01
            • 2019-02-09
            • 2019-11-29
            • 2018-07-02
            • 2017-03-30
            • 2013-09-09
            • 2018-10-04
            相关资源
            最近更新 更多