LoginSignup
0
0

More than 3 years have passed since last update.

Vue.jsで子コンポーネントのイベントを親コンポーネントで実装したい場合

Last updated at Posted at 2020-05-11

Vue.jsで子コンポーネントのイベントを親コンポーネントで実装したい場合

各ページの共通ボタン付きのヘッダーをコンポーネント化し、それぞれのページの子コンポーネントとして実装することは多いかと思います。
ただ、同じヘッダーボタンでもページ毎に処理内容を変えたい等、子コンポーネントのボタンイベントを呼び出す親コンポーネント別で実装したかったのですが、どう実装するか探すのに少し苦労したため、ご参考までに。

子コンポーネント

child.vue
<template>
    <div class="header">
        <a @click="save" class="btn-flat-bottom-border">
            <span>save</span>
        </a>
        <a @click="add" cass="btn-flat-bottom-border">
            <span>add</span>
        </a>
        <a @click="del" class="btn-flat-bottom-border">
            <span>del</span>
        </a>
        <a @click="out" class="btn-flat-bottom-border">
            <span>out</span>
        </a>
        <a @click="setting" class="btn-flat-bottom-border">
            <span>setting</span>
        </a>
    </div>
</template>

<script>
export default {
    methods:{
        save:function(){
            this.$emit('saveChild');
        },
        add:function(){
            this.$emit('addChild');
        },
        del:function(){
            this.$emit('delChild');
        },
        out:function(){
            this.$emit('outChild');
        },
        setting:function(){
            this.$emit('settingChild');
        }
    }
}
</script>

親コンポーネント

parent.vue
<template>
    <div>
        <headerVue @saveChild="saveParent" @addChild="addParent" @delChild="delParent" @outChild="outParent" @settingChild="settingParent"/>
    </div>
</template>

<script>
import headerVue from '../components/header.vue'

export default {
    methods:{
        saveParent:function(){
            alert("saveボタン押下")
        },
        addParent:function(){
            alert("addボタン押下")
        },
        delParent:function(){
            alert("delボタン押下")
        },
        outParent:function(){
            alert("outボタン押下")
        },
        settingParent:function(){
            alert("settingボタン押下")
        }
    }
}
</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