今回のコード
HTML側
<b-modal
v-model="state.is_confirm_modal_open"
title="モーダル画面"
@shown="focusMyElement"
><input type="text" id="focusThis"></b-modal>
<button @click="open">スイッチ</button>
JS側
let vm = new Vue({
el: '#app',
data:{
return{
state:{
is_confirm_modal_open: false,
}
}
},
methods: {
open(){
this.state.is_confirm_modal_open = true,
},
focusMyElement(){
document.getElementById('focusThis').focus();
},
});
ブラウザに「スイッチ」と書かれたボタンが表示される。
それを押すと、モーダル画面が出現し、画面内には入力欄が用意されている。
開いた時点で、その入力欄がフォーカスされている状態になっている。
解説
モーダル画面表示まで
画面で「スイッチ」ボタンを押すと、
スイッチ
<button @click="open">スイッチ</button>
↑ここの@click(v-on:click)により、「openメソッド」が起動する。
openメソッド
open(){
this.state.is_confirm_modal_open = true,
},
↑JS側のここに「openメソッド」があって、「this.state.is_confirm_modal_open」をtrueに切り替える。
dataの中
data:{
return{
state:{
is_confirm_modal_open: false,
}
}
},
↑「this.state.is_confirm_modal_open」は、JS側のdata内で初期値「false」で定義されている。
これがtrueに変えられることで、
b-modalの中
<b-modal
v-model="state.is_confirm_modal_open"
HTML側のb-model内のv-model="state.is_confirm_modal_open"
がtrueとなり、
モーダルが表示される。
inputタグへのフォーカス
モーダルが表示された際、
b-modalの中
@shown="focusMyElement"
により、「focusMyElementメソッド」が発火する。
(ちなみに、この@shownは@showとは違うディレクティブになるので注意)
このメソッドは、
focusMyElementメソッド
focusMyElement(){
document.getElementById('focusThis').focus();
},
このようになっていて、id="focusThis"の付いている要素にフォーカスされる、といった仕組み。