0
0

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】子コンポーネントから親コンポーネントに関数をemitするっていうアイデアを思いついた

Last updated at Posted at 2021-06-21

子コンポーネントと親コンポーネントを行ったり来たり。
思いついたので公開しておく。(世間的には当たり前かもしれない)

オブジェクトにメソッドを持たせることを思いつけばemitもできてたのしい
なにかの拍子に役に立つかも。

CodePen
https://codepen.io/fruitriin/pen/wvJbBXm?editors=0001

parent.vue
<template>
  <div>
    <Child @from-child="emitFromChild" />
    <input type="text" v-model="parentText" />
  </div>
</template>

<script>
import Child from "@/components/Child.vue";

export default {
  components: {
    Child,
  },
  data() {
    return {
      parentText: "from Parent !",
    };
  },
  methods: {
    emitFromChild(obj) {
      console.log("I'm Parent");
      obj.fireFromParent(this.parentText);
    },
  },
};
</script>
Child.vue
<template>
  <div>
    <button @click="emitFromChild">Emit!</button>
    <p>{{ text }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: "",
    };
  },
  methods: {
    emitFromChild() {
      this.$emit("fromChild", { fireFromParent: this.fireFromParent });
    },
    // このメソッドは子コンポーネントのスコープを持っている
    fireFromParent(text) {
      this.text = text;
    },
  },
};
</script>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?