如何在 Vue.js component/page created/load 上显示模态

How to show modal on component/page created/load in Vue.js

我是 Vue.js 的新手,我对模态感到很吃力。我想在用户导航到某个组件时首先加载模态 window 。我尝试创建一些示例模式,如果我单击一个按钮并触发 $('#modalId').modal('show'),它就会打开。但是当我尝试从 Vue 的 created () {...} 执行相同的命令时,它不会打开模式 window。我不想通过单击按钮打开模式 window,我想在 page/component 加载时打开。

    <!-- This works fine -->
    <button class="btn btn-dark" @click="openModal" data-target="#loginModal">Open modal</button>

    <!-- MODAL -->
    <div class="modal" ref="modal" id="loginModal" data-keyboard="false" data-backdrop="static">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Insert required data</h5>
          </div>
          <div class="modal-body">
            <form>
              <div class="form-group">
                <label for="username">Username</label>
                <input type="text" class="form-control">
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button class="btn btn-primary" data-dismiss="modal">Submit</button>
            <a href="#" @click="logout" data-dismiss="modal">
              <span>{{ $t('pages.userIconInHeader.signOut') }}</span>
            </a>
          </div>
        </div>
      </div>
    </div>

...

export default {
  name: 'test',
  data () {
    return {}
  },
  created () {
    // HERE I WOULD LIKE TO OPEN MODAL. If it's even possible?
    $(document).ready(function () {
      this.openModal()
    })
  },
  methods: {
    openModal () {
      $('#loginModal').modal('show')
    },

...

mounted 中使用而不 $(document).ready(function(){}):

mounted() {
  this.openModal();
},

不要混用 jQuery 和 Vue。 Vue 使用 Virtual DOM,您应该根据 Vue 文档更新、显示、隐藏元素,不能使用 jQuery。这是一篇关于在 Vue 中创建模态的文章,希望对您有所帮助 https://alligator.io/vuejs/vue-modal-component/

mounted() {
    this.showModal()
},

methods: {
    showModal() {
     this.$modal.show("model-name")
    },
}

这个可以用来在vuejs中打开模型