彈出視窗

彈出視窗是透過 JavaScript 和 CSS 編寫的簡潔但靈活的對話框提示訊息。它們支援多種使用情況,從使用者通知到完全自訂的內容,並具有一系列有用的子元件、大小、變種、無障礙功能等等。

<div>
  <b-button v-b-modal.modal-1>Launch demo modal</b-button>

  <b-modal id="modal-1" title="BootstrapVue">
    <p class="my-4">Hello from modal!</p>
  </b-modal>
</div>

<!-- b-modal.vue -->

概觀

預設情況下,<b-modal> 在頁腳中有一個 確定取消按鈕。可以透過設定元件上的各種 props 來自訂這些按鈕。你可以自訂按鈕的大小、停用按鈕、隱藏取消按鈕(例如 ok-only)、使用 ok-variantcancel-variant props 選擇變種(例如 danger 代表紅色的確定按鈕),並使用 ok-titlecancel-title props 或使用命名槽 modal-okmodal-cancel來提供自訂按鈕內容。

<b-modal> 預設開啟關閉 ESC 按鍵(預設啟用)、背景點按關閉(預設啟用)和頁眉中的 X 關閉按鈕(預設啟用)。這些功能可以透過設定 no-close-on-escno-close-on-backdrophide-header-close props 來關閉。

你可以透過命名槽 modal-title 來覆寫彈出視窗標題,透過 modal-header 槽來完全覆寫標題,並透過 modal-footer 槽來完全覆寫頁腳。

註解:使用 modal-footer 時,預設的 確定取消 按鈕將不會出現。此外,如果您使用 modal-header 時,預設的標題 X 關閉按鈕不會出現,且您也不能使用 modal-title 時。

模組在顯示之前不會在文件中呈現其內容(遲延呈現)。模組在顯示時加載在 <body> 元素<b-modal> 元件的配置不會影響配置,因為它總是呈現為備註評論節點 (<!---->)。您可以改用 static prop 來revert 到舊版本的BootstrapVue版本的行為。

切換模組可見性

有幾種方法可以切換 <b-modal> 的可見性。

使用 v-b-modal 指令

其他元素可以使用 v-b-modal 指令輕鬆顯示模組。

<div>
  <!-- Using modifiers -->
  <b-button v-b-modal.my-modal>Show Modal</b-button>

  <!-- Using value -->
  <b-button v-b-modal="'my-modal'">Show Modal</b-button>

  <!-- The modal -->
  <b-modal id="my-modal">Hello From My Modal!</b-modal>
</div>

<!-- b-modal-directive.vue -->

這個作法會在模組關閉後自動將焦點返回到觸發元素(類似預設 Bootstrap 的功能)。其他切換模組可見性的作法可能需要其他程式碼來實作這個便利性功能。

請參閱下面的 無障礙輔助功能 區段以了解詳細資訊。

使用 this.$bvModal.show()this.$bvModal.hide() 執行個體方法

將 BootstrapVue 安裝為外掛程式,或使用 ModalPlugin 外掛程式時,BootstrapVue 會將 $bvModal 物件注入到每個 Vue 個體中(component、app)。 this.$bvModal 公開幾個方法,其中兩個是用於顯示和隱藏模組

方法 說明
this.$bvModal.show(id) 顯示具有指定 id 的模組
this.$bvModal.hide(id) 隱藏具有指定 id 的模組

兩個方法在呼叫後立即傳回。

<div>
  <b-button id="show-btn" @click="$bvModal.show('bv-modal-example')">Open Modal</b-button>

  <b-modal id="bv-modal-example" hide-footer>
    <template #modal-title>
      Using <code>$bvModal</code> Methods
    </template>
    <div class="d-block text-center">
      <h3>Hello From This Modal!</h3>
    </div>
    <b-button class="mt-3" block @click="$bvModal.hide('bv-modal-example')">Close Me</b-button>
  </b-modal>
</div>

<!-- b-modal-bv-modal-hide-show.vue -->

this.$bvModal 物件也用於顯示 模組訊息方塊

使用 show()hide()toggle() 元件方法

您可以使用 ref 屬性存取模組,然後再呼叫 show()hide()toggle() 方法。

<template>
  <div>
    <b-button id="show-btn" @click="showModal">Open Modal</b-button>
    <b-button id="toggle-btn" @click="toggleModal">Toggle Modal</b-button>

    <b-modal ref="my-modal" hide-footer title="Using Component Methods">
      <div class="d-block text-center">
        <h3>Hello From My Modal!</h3>
      </div>
      <b-button class="mt-3" variant="outline-danger" block @click="hideModal">Close Me</b-button>
      <b-button class="mt-2" variant="outline-warning" block @click="toggleModal">Toggle Me</b-button>
    </b-modal>
  </div>
</template>

<script>
  export default {
    methods: {
      showModal() {
        this.$refs['my-modal'].show()
      },
      hideModal() {
        this.$refs['my-modal'].hide()
      },
      toggleModal() {
        // We pass the ID of the button that we want to return focus to
        // when the modal has hidden
        this.$refs['my-modal'].toggle('#toggle-btn')
      }
    }
  }
</script>

<!-- b-modal-methods.vue -->

hide() 方法接受一個選用字串 trigger 參數,用於定義觸發模組關閉的原因。請參閱以下 防止關閉 區段以了解詳細資訊。

註解:建議使用(在前面區段提到的)this.$bvModal.show()this.$bvModal.hide() 方法,而不是用 $ref 方法。

使用 v-model 屬性

v-model 屬性總是與 <b-modal> 可見狀態自動同步,您可以使用 v-model 顯示/隱藏。

<template>
  <div>
    <b-button @click="modalShow = !modalShow">Open Modal</b-button>

    <b-modal v-model="modalShow">Hello From Modal!</b-modal>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        modalShow: false
      }
    }
  }
</script>

<!-- b-modal-v-model.vue -->

使用 v-model 屬性時,請勿同時使用 visible 屬性。

使用作用域插槽範疇方法

參閱 使用插槽的自訂呈現章節,了解如何使用傳遞給作用域插槽來關閉對話框。

針對 $root 傳送事件

您可以針對 $root 傳送 bv::show::modalbv::hide::modalbv::toggle::modal 事件,第一個參數設定成對話框的 id。第二個參數(選擇性)可以指定關閉對話框後要將焦點返回的元素。第二個參數可以是 CSS 選擇器、元素參考或元件參考(將會將焦點集中在元件的根元素上)。

<div>
  <b-button @click="showModal" ref="btnShow">Open Modal</b-button>
  <b-button @click="toggleModal" ref="btnToggle">Toggle Modal</b-button>

  <b-modal id="modal-1">
    <div class="d-block">Hello From My Modal!</div>
    <b-button @click="hideModal">Close Me</b-button>
    <b-button @click="toggleModal">Toggle Me</b-button>
  </b-modal>
</div>
export default {
  methods: {
    showModal() {
      this.$root.$emit('bv::show::modal', 'modal-1', '#btnShow')
    },
    hideModal() {
      this.$root.$emit('bv::hide::modal', 'modal-1', '#btnShow')
    },
    toggleModal() {
      this.$root.$emit('bv::toggle::modal', 'modal-1', '#btnToggle')
    }
  }
}

注意:建議使用前面一個章節提到的 this.$bvModal.show()this.$bvModal.hide() 方法,而不是傳送 $root 事件。

避免關閉

為了避免 <b-modal> 關閉(例如驗證失敗時),您可以呼叫傳遞給您的 ok確定按鈕)、cancel取消按鈕)、close(對話框標題關閉按鈕)和 hide 事件處理器的 event 物件的 .preventDefault() 方法。請注意,在使用時 .preventDefault() 必須同步呼叫,因為不支援非同步。

<template>
  <div>
    <b-button v-b-modal.modal-prevent-closing>Open Modal</b-button>

    <div class="mt-3">
      Submitted Names:
      <div v-if="submittedNames.length === 0">--</div>
      <ul v-else class="mb-0 pl-3">
        <li v-for="name in submittedNames">{{ name }}</li>
      </ul>
    </div>

    <b-modal
      id="modal-prevent-closing"
      ref="modal"
      title="Submit Your Name"
      @show="resetModal"
      @hidden="resetModal"
      @ok="handleOk"
    >
      <form ref="form" @submit.stop.prevent="handleSubmit">
        <b-form-group
          label="Name"
          label-for="name-input"
          invalid-feedback="Name is required"
          :state="nameState"
        >
          <b-form-input
            id="name-input"
            v-model="name"
            :state="nameState"
            required
          ></b-form-input>
        </b-form-group>
      </form>
    </b-modal>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        name: '',
        nameState: null,
        submittedNames: []
      }
    },
    methods: {
      checkFormValidity() {
        const valid = this.$refs.form.checkValidity()
        this.nameState = valid
        return valid
      },
      resetModal() {
        this.name = ''
        this.nameState = null
      },
      handleOk(bvModalEvent) {
        // Prevent modal from closing
        bvModalEvent.preventDefault()
        // Trigger submit handler
        this.handleSubmit()
      },
      handleSubmit() {
        // Exit when the form isn't valid
        if (!this.checkFormValidity()) {
          return
        }
        // Push the name to submitted names
        this.submittedNames.push(this.name)
        // Hide the modal manually
        this.$nextTick(() => {
          this.$bvModal.hide('modal-prevent-closing')
        })
      }
    }
  }
</script>

<!-- b-modal-prevent-closing.vue -->

注意:事件 okcancelclose 分別由對話框內建的確定取消和標題關閉(X)按鈕傳送。如果您在 modal-footer 插槽提供了自己的按鈕,或隱藏了頁尾,則預設情況下這些事件不會被發射。在這種情況下,使用 hide 事件來控制取消對話框關閉。即使傳送 okcancelclosehide 事件依然會被傳送。

okcancelclosehide event 物件 (BvModalEvent) 包含一些屬性和方法

屬性或方法 類型 說明
preventDefault() 方法 如果呼叫,會避免對話框關閉
trigger 屬性 下列之一:如果按下 Esc 鍵,ok(預設確定已按)、cancel(預設取消已按)、escbackdrop(如果按了背景)、headerclose(如果按了標題的 X 按鈕)、第一個提供給 hide() 方法的參數,否則為 null
target 屬性 對話框元素的參考
vueTarget 屬性 對話框的 Vue VM 實例的參考
componentId 屬性 模態對話框的 ID

你可以通過傳遞一個參數給元件的 hide() 方法,進階控制 trigger 的值(也就是偵測是什麼按鈕或動作讓模態對話框關閉)。

備註:hide() 的參數嚴格為 'ok''cancel''headerclose' 時,才會發出 okcancelclose 事件。傳遞給 hide() 的參數,會放入事件物件的 trigger 屬性。,

使用格狀系統

在模態對話框中使用 Bootstrap 格狀系統,方法是在模態對話框主體中,嵌套 <b-container fluid>。然後,使用一般的格狀系統 <b-row>(或 <b-form-row>)和 <b-col>,如同你在其他地方使用的方式一樣。

工具提示和浮動提示

可以根據需要在模態對話框中置入工具提示和浮動提示。當模態對話框關閉時,會自動清除其中所有的工具提示和浮動提示。工具提示和浮動提示會自動附加到模態對話框元素(確保正確的 z-index),但是你可以指定容器 ID 來覆寫它們附加的位置(詳情請參閱工具提示和浮動提示文件)。

<div>
  <b-button v-b-modal.modalPopover>Show Modal</b-button>

  <b-modal id="modalPopover" title="Modal with Popover" ok-only>
    <p>
      This
      <b-button v-b-popover="'Popover inside a modal!'" title="Popover">Button</b-button>
      triggers a popover on click.
    </p>
    <p>
      This <a href="#" v-b-tooltip title="Tooltip in a modal!">Link</a> will show a tooltip on
      hover.
    </p>
  </b-modal>
</div>

<!-- b-modal-popover.vue -->

延遲載入和靜態模態對話框

預設情況下,模態對話框不會在文件呈現其內容,直到它們顯示(延遲呈現)。可見的模態對話框,會附加到 <body> 渲染元素。當 <b-modal> 元件以 placeholder 註解節點(<!---->)的形式呈現為放置於 DOM 的位置時,不會影響版面配置。由於傳送門的流程,內容的變更可能需要兩個或更多個 $nextTick 才能被渲染到目標。,

static 屬性設為 true,可以在文件「就地」呈現模態對話框(也就是 <b-modal> 元件放置在文件中的位置)。注意,即使當 statictrue 時,模態對話框不可見/未顯示,模態對話框的內容仍會在 DOM 中呈現。若要讓 static 模態對話框延遲呈現,也要將 lazy 屬性設為 true。然後,只有當模態對話框可見時,它才會出現在文件。注意,當處於 static 模式時,<b-modal> 元件的位置可能會影響文件和模態對話框的版面配置。

如果 static 屬性不是 truelazy 屬性不會有任何效果(非靜態模態對話框將總是延遲呈現)。

樣式設定、選項和自訂

彈出視窗有三個選用的大小,可透過 size 來設定。這些大小在特定中斷點啟動,以避免在較狹窄的視窗中出現水平捲軸。有效的選用大小為 smlgxl

<div>
  <b-button v-b-modal.modal-xl variant="primary">xl modal</b-button>
  <b-button v-b-modal.modal-lg variant="primary">lg modal</b-button>
  <b-button v-b-modal.modal-sm variant="primary">sm modal</b-button>

  <b-modal id="modal-xl" size="xl" title="Extra Large Modal">Hello Extra Large Modal!</b-modal>
  <b-modal id="modal-lg" size="lg" title="Large Modal">Hello Large Modal!</b-modal>
  <b-modal id="modal-sm" size="sm" title="Small Modal">Hello Small Modal!</b-modal>
</div>

<!-- b-modal-sizes.vue -->

size 屬性對應到 .modal-<size> 類別。

捲動長內容

當彈出視窗變得超過使用者的視窗或裝置時,它們會獨立於頁面本身捲動。試試看下面的示範,就能理解我們的用意。

<div>
  <b-button v-b-modal.modal-tall>Launch overflowing modal</b-button>

  <b-modal id="modal-tall" title="Overflowing Content">
    <p class="my-4" v-for="i in 20" :key="i">
      Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis
      in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
    </p>
  </b-modal>
</div>

<!-- b-modal-scroll-overflow.vue -->

你也可以透過將 scrollable 屬性設定為 true 來建立可捲動的彈出視窗,允許捲動彈出視窗主體。

<div>
  <b-button v-b-modal.modal-scrollable>Launch scrolling modal</b-button>

  <b-modal id="modal-scrollable" scrollable title="Scrollable Content">
    <p class="my-4" v-for="i in 20" :key="i">
      Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis
      in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
    </p>
  </b-modal>
</div>

<!-- b-modal-scrollable-content.vue -->

垂直置中的彈出視窗

透過設定 centered 屬性,將你的彈出視窗垂直置中在視窗中。

<div>
  <b-button v-b-modal.modal-center>Launch centered modal</b-button>

  <b-modal id="modal-center" centered title="BootstrapVue">
    <p class="my-4">Vertically centered modal!</p>
  </b-modal>
</div>

<!-- b-modal-center-vertically.vue -->

請隨時將垂直 centeredscrollable 混搭使用。

變體

透過設定 header-bg-variantheader-text-variantbody-bg-variantbody-text-variantfooter-bg-variantfooter-text-variant 屬性來控制標題、頁尾和主體背景以及文字變體。使用任何標準的 Bootstrap 變體,例如 dangerwarninginfosuccessdarklight 等。

標題的底部邊框和頁尾的頂部邊框變體可以分別透過 header-border-variantfooter-border-variant 屬性來控制。

<template>
  <div>
    <b-button @click="show=true" variant="primary">Show Modal</b-button>

    <b-modal
      v-model="show"
      title="Modal Variants"
      :header-bg-variant="headerBgVariant"
      :header-text-variant="headerTextVariant"
      :body-bg-variant="bodyBgVariant"
      :body-text-variant="bodyTextVariant"
      :footer-bg-variant="footerBgVariant"
      :footer-text-variant="footerTextVariant"
    >
      <b-container fluid>
        <b-row class="mb-1 text-center">
          <b-col cols="3"></b-col>
          <b-col>Background</b-col>
          <b-col>Text</b-col>
        </b-row>

        <b-row class="mb-1">
          <b-col cols="3">Header</b-col>
          <b-col>
            <b-form-select
              v-model="headerBgVariant"
              :options="variants"
            ></b-form-select>
          </b-col>
          <b-col>
            <b-form-select
              v-model="headerTextVariant"
              :options="variants"
            ></b-form-select>
          </b-col>
        </b-row>

        <b-row class="mb-1">
          <b-col cols="3">Body</b-col>
          <b-col>
            <b-form-select
              v-model="bodyBgVariant"
              :options="variants"
            ></b-form-select>
          </b-col>
          <b-col>
            <b-form-select
              v-model="bodyTextVariant"
              :options="variants"
            ></b-form-select>
          </b-col>
        </b-row>

        <b-row>
          <b-col cols="3">Footer</b-col>
          <b-col>
            <b-form-select
              v-model="footerBgVariant"
              :options="variants"
            ></b-form-select>
          </b-col>
          <b-col>
            <b-form-select
              v-model="footerTextVariant"
              :options="variants"
            ></b-form-select>
          </b-col>
        </b-row>
      </b-container>

      <template #modal-footer>
        <div class="w-100">
          <p class="float-left">Modal Footer Content</p>
          <b-button
            variant="primary"
            size="sm"
            class="float-right"
            @click="show=false"
          >
            Close
          </b-button>
        </div>
      </template>
    </b-modal>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        show: false,
        variants: ['primary', 'secondary', 'success', 'warning', 'danger', 'info', 'light', 'dark'],
        headerBgVariant: 'dark',
        headerTextVariant: 'light',
        bodyBgVariant: 'light',
        bodyTextVariant: 'dark',
        footerBgVariant: 'warning',
        footerTextVariant: 'dark'
      }
    }
  }
</script>

<!-- b-modal-variants.vue -->

你也可以透過 modal-classcontent-classheader-classbody-classfooter-class 屬性來分別對彈出視窗對話方塊容器、內容(彈出視窗本身)、標題、主體和頁尾套用任意類別。這些屬性都接受字串或字串陣列。

隱藏背景

透過設定 hide-backdrop 屬性來隱藏彈出視窗的背景。

<div>
  <b-button v-b-modal.modal-no-backdrop>Open modal</b-button>

  <b-modal id="modal-no-backdrop" hide-backdrop content-class="shadow" title="BootstrapVue">
    <p class="my-2">
      We've added the utility class <code>'shadow'</code>
      to the modal content for added effect.
    </p>
  </b-modal>
</div>

<!-- modal-no-backdrop.vue -->

請注意,即使背景已隱藏,點擊彈出視窗外還是會關閉彈出視窗。你可以透過在 <b-modal> 上設定 no-close-on-backdrop 屬性來停用此行為。

停用開啟和關閉動畫

若要在彈出視窗開啟和關閉時停用淡出轉場/動畫,只需在 <b-modal> 元件上設定 no-fade 屬性即可。

想要在預設的頁尾有較小或較大的按鈕嗎?只要將 button-size 屬性設定為 'sm'(小さめ)或 'lg'(大きめ)即可。

<div>
  <b-button v-b-modal.modal-footer-sm>Small Footer Buttons</b-button>
  <b-button v-b-modal.modal-footer-lg>Large Footer Buttons</b-button>

  <b-modal id="modal-footer-sm" title="BootstrapVue" button-size="sm">
    <p class="my-2">This modal has small footer buttons</p>
  </b-modal>

  <b-modal id="modal-footer-lg" title="BootstrapVue" button-size="lg">
    <p class="my-2">This modal has large footer buttons</p>
  </b-modal>
</div>

<!-- modal-footer-btn-sizes.vue -->

如果你透過 modal-footer 插槽提供自己的頁尾,button-size 屬性就不會產生任何效果。

你可以以程式方式停用內建底端按鈕。

你可以透過將 cancel-disabledok-disabled 道具分別設為 true 來個別停用取消確定按鈕。將道具設為 false 可以重新啟用按鈕。

要同時停用取消確定按鈕,只要將 busy 道具設為 true 即可。將其設為 false 可以同時重新啟用兩個按鈕。

自訂巢狀插槽顯示

<b-modal> 提供了數個命名插槽(其中有些是選擇性的作用域),你可以使用這些插槽來自訂對話框各種區段的內容。

插槽 選擇性的作用域 說明
預設 對話框的主要內容
modal-title 放入對話框標題的內容
modal-header 放入標頭的內容。取代整個標頭,包含關閉按鈕
modal-footer 放入底端的內容。取代整個底端,包含按鈕
modal-ok 放入底端確定按鈕內的內容
modal-cancel 放入底端取消按鈕內的內容
modal-header-close 放入標頭關閉 (x) 按鈕內的內容

以下是支援選擇性作用域的插槽所使用的作用域

Method 或 Property 說明
ok() 關閉對話框並觸發 okhide 事件,其中 bvModalEvent.trigger = 'ok'
cancel() 關閉對話框並觸發 cancelhide 事件,其中 bvModalEvent.trigger = 'cancel'
close() 關閉對話框並觸發 closehide 事件,其中 bvModalEvent.trigger = 'headerclose'
hide(trigger) 關閉對話框並觸發 hide 事件,其中 bvModalEvent.trigger = trigger (觸發器為選用)
visible 對話框的可見性狀態。如果對話框可見,則為 true;若不可見,則為 false

使用自訂作用域插槽的對話框範例

<template>
  <b-button @click="$bvModal.show('modal-scoped')">Open Modal</b-button>

  <b-modal id="modal-scoped">
    <template #modal-header="{ close }">
      <!-- Emulate built in modal header close button action -->
      <b-button size="sm" variant="outline-danger" @click="close()">
        Close Modal
      </b-button>
      <h5>Modal Header</h5>
    </template>

    <template #default="{ hide }">
      <p>Modal Body with button</p>
      <b-button @click="hide()">Hide Modal</b-button>
    </template>

    <template #modal-footer="{ ok, cancel, hide }">
      <b>Custom Footer</b>
      <!-- Emulate built in modal footer ok and cancel button actions -->
      <b-button size="sm" variant="success" @click="ok()">
        OK
      </b-button>
      <b-button size="sm" variant="danger" @click="cancel()">
        Cancel
      </b-button>
      <!-- Button with custom close trigger value -->
      <b-button size="sm" variant="outline-secondary" @click="hide('forget')">
        Forget it
      </b-button>
    </template>
  </b-modal>
</template>

<!-- b-modal-scoped-slots.vue -->

多重對話框支援

與原生 Bootstrap v4 不同,BootstrapVue 支援同時開啟多個對話框。

若要停用特定對話框的堆疊,只要在 <b-modal> 元件上設定 no-stacking 道具即可。這將在顯示另一個對話框之前隱藏對話框。

<div>
  <b-button v-b-modal.modal-multi-1>Open First Modal</b-button>

  <b-modal id="modal-multi-1" size="lg" title="First Modal" ok-only no-stacking>
    <p class="my-2">First Modal</p>
    <b-button v-b-modal.modal-multi-2>Open Second Modal</b-button>
  </b-modal>

  <b-modal id="modal-multi-2" title="Second Modal" ok-only>
    <p class="my-2">Second Modal</p>
    <b-button v-b-modal.modal-multi-3 size="sm">Open Third Modal</b-button>
  </b-modal>

  <b-modal id="modal-multi-3" size="sm" title="Third Modal" ok-only>
    <p class="my-1">Third Modal</p>
  </b-modal>
</div>

<!-- b-modal-multiple.vue -->

注意事項

  • 避免將 <b-modal> 巢狀放在另一個 <b-modal> 內部,因為它可能會「限制」在父層對話框對話方塊的邊界中(特別是當使用靜態對話框時)。
  • 對於開啟的每個對話框,不透明背景將會逐漸變暗。這是預期的行為,因為每個背景將開啟在其他對話框和背景之上。

BootstrapVue 在公開的 this.$bvModal 物件上提供了幾個內建的 MessageBox 方法。這些方法提供一種方式,可在應用程式的任何位置產生簡單的確定和確認樣式對話框訊息,而不必在您的頁面上明確放置 <b-modal> 元件。

方法 說明
this.$bvModal.msgBoxOk(訊息, 選項) 開啟一個對話框,內容為 訊息,並包含一個確定按鈕
this.$bvModal.msgBoxConfirm(訊息, 選項) 開啟一個對話框,內容為 訊息,並包含取消和確定按鈕

選項 引數是一個可選的組態物件,用於新增標題和調整訊息方塊對話框的樣式。物件屬性對應到 <b-modal> prop,但格式為 camelCase,而不是 kebab-case

這兩個方法都會傳回一個 Promise(對於 IE 11 和舊的瀏覽器支援需要一個多重載入),在對話框隱藏時會解析成一個值。.msgBoxOk() 始終會解析為值 true,而 .msgBoxConfirm() 會解析為 true(按下確定按鈕)、false(按下取消按鈕)或 null(如果透過背景點擊、按下 Esc 或其他方式關閉對話框)。

如果未提供 訊息,這兩個方法都會立刻傳回值 undefined

您可以使用 .then(..).catch(...) 或非同步 await 程式碼樣式(非同步 await 需要使用新式瀏覽器或編譯器)。

確定訊息方塊

範例:確定訊息方塊

<template>
  <div>
    <div class="mb-2">
     <b-button @click="showMsgBoxOne">Simple msgBoxOk</b-button>
     Return value: {{ String(boxOne) }}
    </div>
    <div class="mb-1">
     <b-button @click="showMsgBoxTwo">msgBoxOk with options</b-button>
     Return value: {{ String(boxTwo) }}
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        boxOne: '',
        boxTwo: ''
      }
    },
    methods: {
      showMsgBoxOne() {
        this.boxOne = ''
        this.$bvModal.msgBoxOk('Action completed')
          .then(value => {
            this.boxOne = value
          })
          .catch(err => {
            // An error occurred
          })
      },
      showMsgBoxTwo() {
        this.boxTwo = ''
        this.$bvModal.msgBoxOk('Data was submitted successfully', {
          title: 'Confirmation',
          size: 'sm',
          buttonSize: 'sm',
          okVariant: 'success',
          headerClass: 'p-2 border-bottom-0',
          footerClass: 'p-2 border-top-0',
          centered: true
        })
          .then(value => {
            this.boxTwo = value
          })
          .catch(err => {
            // An error occurred
          })
      }
    }
  }
</script>

<!-- b-modal-msg-box-ok.vue -->

確認訊息方塊

範例:確認訊息方塊

<template>
  <div>
    <div class="mb-2">
     <b-button @click="showMsgBoxOne">Simple msgBoxConfirm</b-button>
     Return value: {{ String(boxOne) }}
    </div>
    <div class="mb-1">
     <b-button @click="showMsgBoxTwo">msgBoxConfirm with options</b-button>
     Return value: {{ String(boxTwo) }}
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        boxOne: '',
        boxTwo: ''
      }
    },
    methods: {
      showMsgBoxOne() {
        this.boxOne = ''
        this.$bvModal.msgBoxConfirm('Are you sure?')
          .then(value => {
            this.boxOne = value
          })
          .catch(err => {
            // An error occurred
          })
      },
      showMsgBoxTwo() {
        this.boxTwo = ''
        this.$bvModal.msgBoxConfirm('Please confirm that you want to delete everything.', {
          title: 'Please Confirm',
          size: 'sm',
          buttonSize: 'sm',
          okVariant: 'danger',
          okTitle: 'YES',
          cancelTitle: 'NO',
          footerClass: 'p-2',
          hideHeaderClose: false,
          centered: true
        })
          .then(value => {
            this.boxTwo = value
          })
          .catch(err => {
            // An error occurred
          })
      }
    }
  }
</script>

<!-- b-modal-msg-box-confirm.vue -->

訊息方塊備註

  • this.$bvModal 注入只在使用完整的 BootstrapVue 外掛程式或 ModalPlugin 外掛程式時可用。如果僅匯入 b-modal 元件,則無法使用。若要僅匯入注入,請使用 BVModalPlugin 外掛程式。
  • 會為每個 Vue 虛擬機(即每個實例化的元件)建立一項新的 $bvModal 注入(mixin),且無法透過直接存取 Vue.prototype 來使用,因為它需要存取該實例的 this$root 內容。
  • 訊息方塊需要瀏覽器支援 Promise。如果您應用程式的目標是舊式瀏覽器,例如 IE 11,請包含提供 Promise 支援的多重載入。如果未偵測到 Promise 支援,那麼訊息方塊方法將立即傳回 undefined
  • 訊息方塊是 <b-modal> 元件的延伸,因此支援大部分 <b-modal> prop(使用 camelCase 格式),但下列 prop 除外: lazystaticbusyvisiblenoStackingokOnlyokDisabledcancelDisabled
  • 當選項中未提供 title(或 titleHtml),則不會顯示標題。
  • 當選項中提供 title(或 titleHtml)時,預設不顯示訊息方塊關閉按鈕。您可以透過在選項中設定 hideHeaderClose: false 來啟用訊息方塊關閉按鈕。
  • 如果訊息方塊在隱藏之前被關閉/銷毀,它們將拋出錯誤(承諾拒絕)。始終包含 .catch(errHandler) 拒絕處理常式,即使使用非同步 await 樣式碼也一樣。
  • 當使用 Vue Router(或類似)時,如果在強制模式隱藏之前,路由會變更,則訊息方塊會關閉並拒絕。如果您希望訊息方塊在路由變更時保持開啟,請使用 this.$root.$bvModal 而不是 this.$bvModal
  • 訊息方塊無法在伺服器端渲染 (SSR) 時產生。
  • 訊息方塊 message 目前不支援 HTML 字串,然而,您可以傳遞一個 VNodes 陣列 作為 message,以精細控制標記。您可以使用 Vue 的 this.$createElement 方法產生 VNodes。這也可以用於對話框標題(透過將 VNodes 傳遞至 title 選項),確定按鈕文字(透過 okTitle 選項),以及取消按鈕文字(透過 cancelTitle 選項)。

訊息方塊進階用法

使用 this.$bvModal.msgBoxOk(...)this.$bvModal.msgBoxConfirm(...) 方法產生強制模式時,您可能希望強制模式內容不只是一個字串訊息。如上方的 訊息方塊註解 區段中所述,您可以將 VNodes 的 陣列 傳遞為更複雜內容的訊息和標題。

使用 Vue 的 this.$createElement 方法產生 VNodes。

<template>
  <div>
    <b-button @click="showMsgOk">Show OK message box with custom content</b-button>
  </div>
</template>

<script>
  export default {
    methods: {
      showMsgOk() {
        const h = this.$createElement
        // Using HTML string
        const titleVNode = h('div', { domProps: { innerHTML: 'Title from <i>HTML<i> string' } })
        // More complex structure
        const messageVNode = h('div', { class: ['foobar'] }, [
          h('p', { class: ['text-center'] }, [
            ' Flashy ',
            h('strong', 'msgBoxOk'),
            ' message ',
          ]),
          h('p', { class: ['text-center'] }, [h('b-spinner')]),
          h('b-img', {
            props: {
              src: 'https://picsum.photos/id/20/250/250',
              thumbnail: true,
              center: true,
              fluid: true, rounded: 'circle'
            }
          })
        ])
        // We must pass the generated VNodes as arrays
        this.$bvModal.msgBoxOk([messageVNode], {
          title: [titleVNode],
          buttonSize: 'sm',
          centered: true, size: 'sm'
        })
      }
    }
  }
</script>

<!-- modal-msg-box-advanced.vue -->

透過 $root 事件監聽強制模式變更

若要監聽任何強制模式開啟,請使用

export default {
  mounted() {
    this.$root.$on('bv::modal::show', (bvEvent, modalId) => {
      console.log('Modal is about to be shown', bvEvent, modalId)
    })
  }
}

請參閱本文件中的 事件 區段,以取得已發出的事件完整清單。

可及性

<b-modal> 提供多項可及性功能,包含自動對焦、返回對焦、鍵盤(tab)焦點約束,以及自動化 aria-* 屬性。

注意:本元件的動畫效果會依據 prefers-reduced-motion 媒體查詢而有不同。請參閱我們 可及性文件的降低動作區段,以取得其他詳細資訊。

在多數情況下,aria-labelledbyaria-describedby 屬性會自動出現在強制模式中。

  • 如果您隱藏標頭、提供您自己的標頭,或未提供對話框標題,aria-labelledby 屬性將不會顯示。建議您提供對話框的標題(使用內建標題時)。您可以在視覺上隱藏標題,但仍可透過設定 title-sr-only 屬性而讓螢幕閱讀器使用。如果您沒有標題,您可以透過傳遞一個字串給 aria-label 屬性來提供對話框的標籤。
  • aria-describedby 屬性將永遠指向對話框的主體內容。
  • 如果指定 aria-label 屬性並提供字串值,aria-labelledby 屬性將不會呈現,即使對話框有標題/標頭。

aria-labeltitle-sr-only 屬性新增於 v2.0.0-rc.27 版。

開啟自動對焦

<b-modal> 會在開啟時自動對焦對話框容器

您可以透過傾聽 <b-modal> shown 事件並呼叫元素的 focus() 方法,在 <b-modal> 內預先聚焦某個元素。如果 <b-modal> 內的一個元素已經對焦,<b-modal> 將不會嘗試自動對焦。

<b-modal @shown="focusMyElement">
  <div>
    <b-button>I Don't Have Focus</b-button>
  </div>

  <div>
    <b-form-input></b-form-input>
  </div>

  <div>
    <!-- Element to gain focus when modal is opened -->
    <b-form-input ref="focusThis"></b-form-input>
  </div>

  <div>
    <b-form-input></b-form-input>
  </div>
</b-modal>
export default {
  methods: {
    focusMyElement() {
      this.$refs.focusThis.focus()
    }
  }
}

或者,如果您使用 b-form-* 表單控制,您可以使用 autofocus 屬性在對話框開啟時自動聚焦表單控制。請注意,如果使用了 static 屬性但沒設定 lazy 屬性,autofocus 屬性將不適用於 b-modal,因為 autofocus 會在 b-form-* 控制裝入 DOM 時發生。

如果您想要自動聚焦其中一個內建對話框按鈕(okcancel 或標頭 close 按鈕),您可以設定屬性 auto-focus-button'ok''cancel''close' 之一,而 <b-modal> 將會聚焦特定按鈕(如果存在)。這個功能也適用於對話框訊息方塊。

注意:由於易於存取的原因,不建議自動聚焦對話框內的輸入或控制,因為螢幕閱讀器使用者將不知道輸入的內容(對話框的公告可能不會被說出來)。最好的方式是讓 <b-modal> 聚焦對話框容器,讓對話框資訊告知使用者,然後讓使用者可以選取輸入。

傳回焦點到觸發元素

出於易於存取的原因,在關閉對話框時,最好將焦點傳回觸發對話框開啟的元素。

<b-modal> 將嘗試自動判斷在對話框開啟前哪個元素具有焦點,並在可能的情況下,在對話框隱藏時將焦點傳回該元素。然而,有數種方法和選項可供您指定對話框隱藏之後要傳回焦點的元素。

透過 return-focus 屬性指定回傳焦點元素

您也可以透過設定 return-focus 屬性為下列其中一項,在對話方塊關閉時指定回傳焦點的元素

  • CSS 查詢選擇器字串 (或元素 ID 前加上 #)
  • 組件參考 (已裝載在可對焦元素上,例如 <b-button>)
  • 可對焦的 DOM 元素參考

如果傳遞進入的元素不可對焦,瀏覽器會自行判定焦點為何 (通常為 <body>,這並不理想)

當您使用 <b-modal> 方法 show()hide(),或 v-model 屬性時,這個回傳焦點的方法非常方便。注意此屬性優先執行,高於指定回傳焦點元素的其他方法。

自動回傳焦點

在元素上透過 v-b-modal 指示執行 <b-modal> 開啟時,焦點將自動回傳到這個元素,除非已透過 return-focus 屬性指定某個元素。

透過事件指定回傳焦點

當使用 bv::show::modal 事件 (在 $root 中傳送) 時,您可以指定第二個參數,也就是要回傳焦點的元素。這個參數可接受與 return-focus 屬性相同的類型。

this.$root.$emit('bv::show::modal', 'modal-1', '#focusThisOnClose')

提示:若使用點擊事件 (或類似的事件) 來觸發對話方塊開啟,請傳送事件的 target 屬性

<div>
  <b-button @click="$root.$emit('bv::show::modal', 'modal-1', $event.target)">Open Modal</b-button>
</div>

注意:如果 <b-modal> 已設定 return-focus 屬性,則會忽略透過事件指定的元素。

鍵盤導覽

<b-modal> 內部透過 tab 鍵瀏覽各個元素時,如果焦點嘗試離開對話方塊到文件,將會被帶回對話方塊內。

請避免將對話方塊內元素的 tabindex 設為除 0-1 以外的任何值。這麼做會讓依賴輔助技術的人員難以瀏覽和操作頁面內容,並且會讓某些元素無法透過鍵盤導覽。

如果對話方塊外的某些元素需要可對焦 (例如 TinyMCE),您可以將它們作為 CSS 選擇器新增到 ignore-enforce-focus-selector 屬性中 2.4.0+,例如

<b-modal
  id="some-modal-id"
  title="Modal with TinyMCE Editor"
  ignore-enforce-focus-selector=".tox-tinymce-aux, .moxman-window, .tam-assetmanager-root"
>
  <!-- Modal content with TinyMCE editor here -->
</b-modal>

在某些情況下,您可能需要完全停用強制焦點功能。您可以透過設定屬性 no-enforce-focus 來達成此目的,不過由於這與無障礙性相關,極不推薦這麼做。

v-b-modal 指示無障礙性

有關 v-b-modal 指示無障礙性的注意事項

  • 如果元素不是 <button>(或呈現 <button> 的元件),ARIA role 將設定為 button,也會加入 EnterSpace 的 keydown 活動監聽程式,以及一個 click 監聽程式。
  • 如果元素不是 <button><a>(或呈現上述兩種標籤的元件),則會將 tabindex of 0 加入元素以確保可存取性,除非已設定 tabindex

元件參考

<b-modal>

屬性

所有屬性預設值都 可用於全球設定

屬性
(按一下以依遞增順序排序)
類型
(按一下以依遞增順序排序)
預設值
說明
aria-label
字串明確提供對話框的「aria-label」屬性。若對話框沒有標題,應設定此屬性。否則,「aria-labelledby」將指向對話框的標題。
auto-focus-button
v2.0.0+
字串null指定對話框開啟後,要聚焦哪一個內建按鈕:「ok」、「cancel」或「close」
body-bg-variant
字串套用 Bootstrap 主題變異色之一至主體背景
body-class
ArrayObjectString要套用到「.modal-body」的外包元素的 CSS 類別(或類別)
body-text-variant
字串套用 Bootstrap 主題變異色之一至主體文字
busy
布林值false將預設內建頁腳的「確定」和「取消」按鈕設為停用狀態
button-size
字串內建頁腳按鈕的尺寸:「sm」、「md」(預設)或「lg」
cancel-disabled
布林值false將預設頁腳的「取消」按鈕設為停用狀態
cancel-title
字串'Cancel'預設頁腳「取消」按鈕內要置入的文字字串
cancel-title-html
請小心使用
字串預設頁腳「取消」按鈕內要置入的 HTML 字串
cancel-variant
字串'secondary'按鈕顏色主題變異色,要套用到預設頁腳的「取消」按鈕
centered
布林值false將對話框垂直置中於視窗
content-class
ArrayObjectString要套用到「.modal-content」的外包元素的 CSS 類別(或類別)
dialog-class
ArrayObjectString要套用到「.modal-dialog」的外包元素的 CSS 類別(或類別)
footer-bg-variant
字串套用 Bootstrap 主題變異色之一至頁腳背景
footer-border-variant
字串套用 Bootstrap 主題變異色之一至頁腳邊框
footer-class
ArrayObjectString要套用到「.modal-footer」的外包元素的 CSS 類別(或類別)
footer-tag
v2.22.0+
字串'footer'指定要呈現在頁腳預設標籤位置的 HTML 標籤
footer-text-variant
字串套用 Bootstrap 主題變異色之一至頁腳文字
header-bg-variant
字串將 Bootstrap 主題色變體之一套用於標題背景
header-border-variant
字串將 Bootstrap 主題色變體之一套用於標題邊框
header-class
ArrayObjectString套用於「.modal-header」包裝器元素的 CSS 類別(或類別)
header-close-content
v2.3.0+
字串'&times;'標題關閉按鈕的內容
header-close-label
字串'關閉'標題關閉按鈕上「aria-label」的值
header-close-variant
字串套用於標題關閉按鈕的文字主題色變體
header-tag
v2.22.0+
字串'header'指定要呈現在頁腳預設標籤位置的 HTML 標籤
header-text-variant
字串將 Bootstrap 主題色變體之一套用於標題文字
hide-backdrop
布林值false停用模態背景的繪製
hide-footer
布林值false停用模態頁尾的繪製
hide-header
布林值false停用模態標題的繪製
hide-header-close
布林值false停用模態標題關閉按鈕的繪製
id
字串用於設定繪製內容上的「id」屬性,並用作根據需要產生任何其他元素 ID 的基礎
ignore-enforce-focus-selector
v2.4.0+
陣列字串根據 CSS 選擇器指定某些元素,忽略強制焦點例程
lazy
布林值false當模態設定了「static」屬性時,以延遲載入的方式繪製模態內容
modal-class
ArrayObjectString套用於「.modal」包裝器元素的 CSS 類別(或類別)
no-close-on-backdrop
布林值false停用透過按一下背景來關閉模態的能力
no-close-on-esc
布林值false停用透過按下「ESC」鍵來關閉模態的能力
no-enforce-focus
布林值false停用在模態內保持焦點的強制焦點例程
no-fade
布林值false設定為「true」時,停用元件上的淡入/淡出動畫/過場
no-stacking
布林值false防止其他模態堆疊在此模態上方
ok-disabled
布林值false將預設的頁尾 OK 按鈕設為已停用狀態
ok-only
布林值false停用預設的頁尾取消按鈕的繪製
ok-title
字串'確定'放置在預設的頁尾 OK 按鈕中的文字字串
ok-title-html
請小心使用
字串放置在預設的頁尾 OK 按鈕中的 HTML 字串
ok-variant
字串'primary'套用於預設的頁尾 OK 按鈕的按鈕色彩主題變體
return-focus
HTML 元素物件字串HTML 元素參考、CSS 選擇器或元件參考,可在模態關閉時將焦點返回至該元素。未設定時,將焦點返回至模態開啟前最後有焦點的元素
scrollable
布林值false啟用模態主體的捲動
size
字串'md'設定模態寬度的尺寸。'sm'、'md'(預設值)'lg' 或 'xl'
static
布林值false就地將元件內容繪製在 DOM 中,而非將其傳送到appendTo主體元素
title
字串放置在標題中的文字內容
title-class
ArrayObjectString套用於標題的 CSS 類別(或類別)
title-html
請小心使用
字串包含在標題中的 HTML 字串內容
title-sr-only
布林值false將標題包覆在「.sr-only」包裝器中
title-tag
字串'h5'指定要繪製的 HTML 標籤,取代標題的預設標籤
visible
v-model
布林值false模態的目前可見狀態

注意:支援 HTML 字串(*-html)的屬性在傳遞未處理的使用者所提供的值時,容易受到跨網站腳本 (XSS) 攻擊的威脅。您務必先正確地消毒使用者的輸入資料!

v-model

屬性
事件
visiblechange

格位

名稱
區域控管
說明
預設 Modal 主體內容。選用區域控管
modal-backdrop Modal 背景幕內容
modal-cancel Modal CANCEL 按鈕內容
modal-footer Modal 頁尾內容。同時移除預設的 OK 及 Cancel 按鈕。選用區域控管
modal-header 整個 modal 標題容器內容。同時移除右上角 X 關閉按鈕。選用區域控管
modal-header-close Modal 標題關閉按鈕內容。如果使用 `modal-header` 格位,這個格位將不會顯示
modal-ok Modal OK 按鈕內容
modal-title Modal 標題。如果使用 `modal-header` 格位,這個格位將不會顯示。選用區域控管

事件

事件
(按一下以依遞增順序排序)
參數
說明
bv::modal::hidden
  1. bvModalEvent - BvModalEvent 物件
  2. modalId - Modal ID
Modal 隱藏時在 `$root` 上發射
bv::modal::hide
  1. bvModalEvent - BvModalEvent 物件。呼叫 `bvModalEvent.preventDefault()` 以取消隱藏
  2. modalId - Modal ID
Modal 即將隱藏時於 `$root` 發射。可取消(只要 modal 未強制隱藏)
bv::modal::show
  1. bvModalEvent - BvModalEvent 物件。呼叫 `bvModalEvent.preventDefault()` 以取消顯示
  2. modalId - Modal ID
Modal 即將顯示時於 `$root` 發射。可取消
bv::modal::shown
  1. bvModalEvent - BvModalEvent 物件
  2. modalId - Modal ID
Modal 顯示時於 `$root` 發射
cancel
  1. bvModalEvent - BvModalEvent 物件。呼叫 `bvModalEvent.preventDefault()` 以取消隱藏
當預設 CANCEL 按鈕觸發時,Modal 隱藏前立即觸發。可取消
change
  1. isVisible - modal 的可見性狀態。`true` 表示 modal 可見,`false` 表示不可見
新的 modal 可見性狀態。用於更新 v-model
close
  1. bvModalEvent - BvModalEvent 物件。呼叫 `bvModalEvent.preventDefault()` 以取消隱藏
當預設 header 關閉按鈕觸發時,Modal 隱藏前立即觸發。可取消
hidden
  1. bvModalEvent - BvModalEvent 物件
modal 隱藏後發射
hide
  1. bvModalEvent - BvModalEvent 物件。檢查 `bvModalEvent.trigger` 以找出執行隱藏動作的事件。呼叫 `bvModalEvent.preventDefault()` 以取消隱藏
modal 隱藏前發射。可取消(只要 modal 未強制隱藏)
ok
  1. bvModalEvent - BvModalEvent 物件。呼叫 `bvModalEvent.preventDefault()` 以取消隱藏
當預設 OK 按鈕觸發時,Modal 隱藏前立即觸發。可取消
show
  1. bvModalEvent - BvModalEvent 物件。呼叫 `bvModalEvent.preventDefault()` 以取消顯示
modal 顯示前發射。可取消
shown
  1. bvModalEvent - BvModalEvent 物件
modal 顯示時發射

$root 事件偵聽

你可以在 $root 上發射下列事件來控制 <b-modal>

事件
參數
說明
bv::hide::modal

modalId - 即將隱藏的 modal ID

當這個事件在 `$root` 發射時,將隱藏指定 ID 的 modal
bv::show::modal

modalId - 即將顯示的 modal ID

elIDtoFocusOnClose - 指定 modal 關閉後重新取得焦點的元素參考或 CSS 選擇器(選用)

當這個事件在 `$root` 發射時,將顯示指定 ID 的 modal
bv::toggle::modal

modalId - 切換可視性的對話框 ID

elIDtoFocusOnClose - 指定 modal 關閉後重新取得焦點的元素參考或 CSS 選擇器(選用)

根據其 ID 切換對話框的可見性

匯入個別組件

你可以透過以下命名匯出,將個別組件匯入專案

組件
命名匯出
匯入路徑
<b-modal>BModalbootstrap-vue

範例

import { BModal } from 'bootstrap-vue'
Vue.component('b-modal', BModal)

匯入個別指令

你可以透過以下命名匯出,將個別指令匯入專案

指令
命名匯出
匯入路徑
v-b-modalVBModalbootstrap-vue

範例

import { VBModal } from 'bootstrap-vue'
// Note: Vue automatically prefixes the directive name with 'v-'
Vue.directive('b-modal', VBModal)

以 Vue.js 外掛匯入

此外掛包含所有上述的個別組件和指令。外掛也包含所有組件別名。

命名匯出
匯入路徑
ModalPluginbootstrap-vue

此外掛也自動包含以下外掛

  • BVModalPlugin

範例

import { ModalPlugin } from 'bootstrap-vue'
Vue.use(ModalPlugin)