5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue.js】親コンポーネントから子コンポーネントのメソッドの呼び出し方

Posted at

親コンポーネントから子コンポーネントのメソッドの呼び出し方について簡単にメモしておく。
ちなみに、逆に子コンポーネントから親コンポーネントのメソッドを呼び出す場合は、$emitを使用する。

子コンポーネントのメソッドの呼び出し方

基本的な書き方

子コンポーネントのメソッドを呼び出すポイントは以下の2点になる。
① 子コンポーネントに任意の名前をref属性を使って付ける。

<sample ref="child"/>

$refsを使って子コンポーネントのメソッドを実行する。

this.$refs.child.testMethod();

上記のように書くことで、子コンポーネントのtestMethod()が実行される。

サンプル

親コンポーネントから子コンポーネントのメソッドを呼び出す簡単なサンプルを書いてみた。
親コンポーネントのボタンが押されると子コンポーネントのclear()が呼ばれるようになっている。

親コンポーネント
<template>
	<div>
		<text-box ref="textBox" />
		<button @click="textClear">クリア</button>
	</div>
</template>

<script>
import TextBox from "./components/TextBox.vue";

export default {
	name: "App",
	components: {
		TextBox,
	},
	methods: {
		textClear() {
			this.$refs.textBox.clear();
		},
	},
};
</script>
子コンポーネント
<template>
	<div>
		<h2>名前:</h2>
		<input type="text" v-model="playerName" />
	</div>
</template>

<script>
export default {
	name: "text-box",

	data() {
		return {
			playerName: "",
		};
	},
	methods: {
		clear() {
			this.playerName = "";
		},
	},
};
</script>
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?