2

Bootstrap Vue を使用してモーダル ウィンドウを表示する Vue CLI アプリ (Webpack テンプレート) を構築しています。次のように、Vue コンポーネントのフックからプログラムでモーダルを表示しようとしています (プログラムでモーダルを呼び出すには、 Bootstrap Vue のドキュメントを参照してください)。mounted()

<script>
export default {
  name: 'ButtonComponent',

  mounted() {
    const showModal = sessionStorage.getItem('showModal');
    if (showModal === 'yes') this.$refs.myModal.show();
  }
}
</script>

これはうまくいきます。setTimeout()ただし、次のような関数を導入すると、これを機能させることができません。

<script>
export default {
  name: 'ButtonComponent',

  mounted() {
    const showModal = sessionStorage.getItem('showModal');
    if (showModal === 'yes') setTimeout(() => this.$refs.myModal.show(), 3500);
  }
}
</script>

3.5 秒後にモーダルが表示されないのはなぜですか? console.log()タイムアウトが機能し、そこからメッセージを送信しようとしたため、それを知っています。タイマー内で Vue JS インスタンスが利用できないことが原因である可能性があると考えたので、 a を宣言しconst self = this;て呼び出してみsetTimeout(() => self.$refs.myModal.show(), 3500);ましたが、どちらも役に立ちませんでした。ここで何が欠けていますか?

4

1 に答える 1

1

構文的に言えば、正しいです。アロー関数を使用すると、これは最初に呼び出されたコンテキストにバインドされます。あなたの場合、これは setTimeout 内で Vue インスタンスを意味します。次のようないくつかのconsole.log呼び出しを実行してみてください。

setTimeout(() => {
  console.log(this); // the vue instances
  console.log(this.$refs); // the $refs
  console.log(this.$refs.myModal); // the modal $ref
}, 3500)

$ref が存在することを確認するだけです。myModalコンポーネントがまだバインドされていない可能性がありますか?

于 2018-08-16T12:23:23.537 に答える