如何使用Vue关闭Modal de Materialize CSS

时间:2018-10-13 06:21:31

标签: vue.js materialize

如果验证正确,但我找不到表格,我正在尝试关闭Modal of Materialize CSS。

最简单的事情是进行类型验证: v-if =“ showModal”,它可以工作,但保留了Modal的背景,尽管单击不会消失。背景是一个名为“模态叠加”的类

这是我的代码:

     <i class="material-icons modal-trigger tooltipped" style="margin-left: 2px; 
     color:#ffc107; cursor:pointer;" @click="getById(article), fillSelectCategories(), 
     titleModal='Edit', type='edit'" data-target="modal1">edit</i>

我从MaterilizeCSS的JS文件中导入了M

import M from "materialize-css/dist/js/materialize.min";

方法:

    update(){
       var elem = document.querySelectorAll('.modal'); 
       var instance = M.Modal.getInstance(elem);
       console.log(instance)

返回“未定义”

我也在update()方法上尝试过:

var elem = document.querySelectorAll('.modal');
elem.close();
M.Modal.close()

我从mount初始化了模态,它可以正常工作,但在需要时无法关闭它。

mounted(){
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems, options);
}

但是我知道还有什么可以尝试的:(

1 个答案:

答案 0 :(得分:1)

很难不深入研究代码就知道为什么事情对您不起作用,但是我已经创建了这个简单的示例来演示如何实现。.

new Vue({
  el: "#app",
  data: {
    modalInstance: null,
    closeAfterTimeElapsed: true,
    seconds: 1
  },
  mounted() {
    const modal = document.querySelector('.modal')
    this.modalInstance = M.Modal.init(modal)

    const select = document.querySelector('select');
    M.FormSelect.init(select);

    M.updateTextFields();
  },
  methods: {
    handleClick() {
      if (this.closeAfterTimeElapsed) {
        setTimeout(() => { this.modalInstance.close() }, this.seconds * 1000)
      }
    }
  }
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>


<div id="app">

  <!-- Modal Trigger -->
  <button @click="handleClick" data-target="modal1" class="btn modal-trigger">Modal</button>
  
  <!-- Modal Structure -->
  <div id="modal1" class="modal">
    <div class="modal-content">
      <h4>Modal Header</h4>
      <p>A bunch of text</p>
    </div>
    <div class="modal-footer">
      <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a>
    </div>
  </div>

  <br>
  <br>

  <div class="row">
    <div class="input-field col s6">
      <select v-model="closeAfterTimeElapsed">
        <option :value="false">False</option>
        <option :value="true">True</option>
      </select>
      <label>Close Modal After</label>
    </div>

    <div class="input-field col s6">
      <input id="seconds" type="number" v-model="seconds">
      <label for="seconds">Seconds</label>
    </div>
  </div>
  
</div>

See this JSFiddle