LoginSignup
3
0

More than 1 year has passed since last update.

Vue.jsの不思議【emit】【複数の引数】

Last updated at Posted at 2022-04-26

emitの基本

子→親へデータを渡す場合、emitを使用する

emitの書き方

this.$emit("親で実行する関数名", "引数1","引数2","引数3");

引数は何個でも取れる

App.vue
<template>
  <div>
    <child @parent="test" />
  </div>
</template>

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

export default {
  components: {
    Child,
  },
  methods: {
    test(arg) {
      console.log("test", arg);
    },
  },
};
</script>

//コンソール
test 
テストメッセージ 
Child.vue
<template>
  <div>
    <button @click="click">親にメッセージを渡す</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newMessage: "テストメッセージ",
    };
  },
  methods: {
    click() {
      this.$emit("parent", newMessage);
    },
  },
};
</script>

これでOK

親をこう書き換えても同じ動作をする

App.vue
<child @parent="test" />
App.vue
<child @parent="test($event)" />

プロパティに直接代入することも可能である

App.vue
<template>
  <div>
    {{ message }}
    <child @parent="message = $event" />
  </div>
</template>

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

export default {
  components: {
    Child,
  },

  data() {
    return {
      message: "",
    };
  },
};
</script>

要するに

<child @parent="ここ!!!" />

ここ!!!にはjavaScriptが書けるのである

親側で条件分岐する

子からのイベントで親の関数を条件付きで実行したい場合

↓だと関数が実行されない

App.vue
<template>
  <div>
    <child @parent="flag ? test1 : test2" />
  </div>
</template>

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

export default {
  components: {
    Child,
  },
  computed: {
    flag() {
      return false;
    },
  },
  methods: {
    test1(arg) {
      console.log("true",arg);
    },
    test2(arg) {
      console.log("false",arg);
    },
  },
};
</script>

↓で正しく実行される

App.vue
<template>
  <div>
    <child @parent="flag ? test1($event) : test2($event)" />
  </div>
</template>

<script>
  //上と同じため省略
</script>

//コンソール
false 
テストメッセージ 

おそらく、

@parent

が実行されたときに

<child @parent="flag ? test1 : test2" />

true,falseの判定だけ実行し、実際の関数は実行されないのであろう

<child @parent="flag ? test1($event) : test2($event)" />

なので関数を実行する()が必要である

<child @parent="test1" />

関数のみの場合、関数を実行してくれる

emitの第二引数

しかしこの書き方だと、emitに第二引数があった場合、どうするのだろうか?

<child @parent="flag ? test1($event) : test2($event)" />

私は第二引数を使わずに引数が2つあったらオブジェクトにして渡していたが、
もっといいやり方があるのかもしれない

vue3だと何か変化があったりするのかもしれない

---環境---
mac
vue2.6.11
node 最新LTS

3
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
3
0