【问题标题】:why b-modal is not invoked when created in Vue?为什么在Vue中创建时不调用b-modal?
【发布时间】:2021-09-24 08:16:15
【问题描述】:

我想在组件创建但没有发生时调用 b-modal。然而,在单击按钮时,会调用模态。我们该如何解决这个问题?

<template>
  <b-container>
    <button @click="$bvModal.show('modal1')">Show</button>
    <b-modal id="modal1" title="Loading" hide-footer no-close-on-backdrop>
      <p>Preparing the Application, Please wait</p>
    </b-modal>
  </b-container>
</template>

<script>
export default {
  data() {
    return {};
  },
  created() {
    this.showModal();
  },
  methods: {
    showModal() {
      this.$bvModal.show("modal1");
    },
  },
};
</script>

【问题讨论】:

  • 我不知道为什么,但是我们这里的 cmets 消失了。无论如何,如果你觉得my answer 帮助了你,你可以accept my answer :)

标签: vue.js vuejs2 bootstrap-modal bootstrap-vue


【解决方案1】:

使用mounted 钩子代替created

created钩子被调用时,组件还没有模板,所以所有的子组件还没有实例化。您只能访问道具和初始数据。 因此不会做任何事情。

mounted 中,您确定所有内容都已实例化,包括b-modal 组件。所以调用$bvModal.show() 应该可以工作:)

【讨论】:

    【解决方案2】:

    当你想与 HTML 元素交互时,最好使用mounted 钩子。

    根据Vue Lifecycle diagramAPI documentation,在mounted钩子中,元素已经被渲染(不保证子元素),所以你可以和他们交互。

    同时,在created 挂钩中,您只能访问数据。

    简而言之,在您的情况下,mounted 挂钩是解决方案。

    【讨论】:

      【解决方案3】:
      <template>
        <b-container>
          <button @click="$refs.modal1.show()">Show</button>
          <b-modal ref=modal1 id="modal1" title="Loading" hide-footer no-close-on-backdrop>
            <p>Preparing the Application, Please wait</p>
          </b-modal>
        </b-container>
      </template>
      
      <script>
      export default {
        data() {
          return {};
        },
        mounted() {
          this.$refs.modal1.show();
        }
      };
      </script>
      

      【讨论】:

      • 请说明您是如何解决问题的
      • 在创建的模态尚未创建。但是在挂载中它是,所以你只需要在那一刻启动它
      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 2020-09-08
      • 2021-05-17
      • 2020-07-13
      • 2021-07-06
      • 2021-11-03
      • 2018-10-04
      • 1970-01-01
      相关资源
      最近更新 更多