###### tags: `Vue` `BootStrap5` modal` {%hackmd BJrTq20hE %} # Vue店商網頁-modal元件化 把modal元件化的優點就是可以重複使用該元件,而且可以利用ref控制modal的開關,完全封裝modal到元件內。 以下1. 2.驟範例都是在component內 ## 1.複製Bs5的modal到template中 ```htmlembedded= <template> <!-- 加上ref--> <div class="modal" tabindex="-1" aria-hidden="true" ref="demo"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>Modal body text goes here.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </template>> ``` ## 2.在script中import Bs的modal,並且創造modal實體,後加入modal的控制 ```javascript= import BsModal from 'bootstrap/js/dist/modal' export default { data () { return { // 為了在mounted創建modal實體先在data設定一個空字串的變數。 bsModal: '' } }, methods: { // 下面是Bs內建的開與關,只是另外用函式包起來。 open () { this.bsModal.show() }, close () { this.bsModal.hide() } }, mounted () { // 創建modal實體 this.bsModal = new BsModal(this.$refs.demo) } } ``` ## 3.在其他component import modal component ```htmlembedded= <template> <h1>我是其他component</h1> // 把import的DemoModal加上ref <DemoModal ref="demo"/> </template> ``` ```javascript= import DemoModal from '@/component/DemoModal.vue' export default { components: { DemoModal }, // 利用ref使用DemoModal內的函式 methods: { openModal () { this.$refs.demo.open() }, closeModal () { this.$refs.demo.close() } } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up