LoginSignup
2
5

More than 3 years have passed since last update.

vue.js 子から親へイベントを渡す

Last updated at Posted at 2019-10-03

子から親へイベントを渡す $emit

emitは 放つ というような意味。

参考
https://qiita.com/fukuman/items/b0bc84081ad0d2bc522a

親コンポーネント Welcome
子コンポーネント SessionNew

1. 子コンポーネントからイベントを渡す

session/new.vue
// templateは省略

methods: {
    loginUser: function() {
      axios
      .post('/login',
      {
        user: {
          email: this.user.email,
          password: this.user.password,
          password_confirmation: this.user.password_confirmation
        }
      })
      .then((res) => {
        console.log(res.data)
        this.$emit('isLogin') // <=== 親コンポーネントに isLogin というイベントを渡す
        this.$bvModal.hide('session-new-modal')
      }, (error) => {
        console.log(error)
      })
    }
  }

2. 子コンポーネントからイベントを受け取る

子コンポーネントsession-newのプロパティに設定する

@子から受け取ったイベント名="実行したい親コンポーネントのメソッド"
welcome.vue
<template>
  <div>
    <session-new @isLogin="loginMessage"></session-new>
  </div>
</template>

3. 子コンポーネントのイベントをきっかけに、親コンポーネントのメソッドを実行する

イベントを受け取ったら、ログインしましたというメッセージを表示する

welcome.vue

<template>
  <div>
    <p v-show="user.showMessage">ログインしました</p>
    <session-new @isLogin="loginMessage"></session-new>
  </div>
</template>

data: function () {
  return {
    user: {
      showMessage: false
    }
  },
  methods: {
    loginMessage: function() {
      console.log('loginMessage called')
      this.user.showMessage = true
    }
  }
}
2
5
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
2
5