Warning: Undefined array key 1 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 12
Warning: Undefined array key 2 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 15
Warning: Undefined array key 3 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 18
Warning: Undefined array key 4 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 21
Warning: Undefined array key 1 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 24
Warning: Undefined array key 2 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 27
Warning: Undefined array key 3 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 30
Warning: Undefined array key 4 in /home/naoooooo8/naoya-ono.com/public_html/blog/wp-content/themes/sango-theme-poripu/library/functions/prp_content.php on line 33
このページでは、Vue.jsの親コンポーネントから子コンポーネントのメソッドを呼び出す方法について紹介します。
やり方
やり方は次の通りです。
- 子コンポーネントにref属性を使って任意の名前をつける。
- 親コンポーネントのメソッド内から子コンポーネントのイベントを発火
1. 子コンポーネントにref属性を使って任意の名前をつける
まずは子コンポーネントにref属性を使って名前をつけます。
Parent.vue
<child-component ref="child"></child-component>
このように記述することで、親コンポーネントから子コンポーネントを参照できるようになります。
上の例では、「child」という名前にしていますが、なんでもOKです。
わかりやすい名前をつけましょう。
2. 親コンポーネントのメソッド内から子コンポーネントのイベントを発火
続いて、親コンポーネントから子コンポーネントのイベントを発火します。
Parent.vue
methods: {
showModal: function() {
// 子コンポーネントのメソッド呼び出し
this.$refs.child.showModal()
}
}
呼び出し方法は「this.$refs.ref属性に指定した名前.呼び出したいイベント名」のように書きます。
上の例の場合、子コンポーネントにある「showModal()」メソッドが呼ばれるようになります。
Child.vue
methods: {
showEditModal: function(){
this.showModal = true
this.showModalBg = true
}



