Home > Mobile >  Multiple buttons in the child component with the methods in the parent component
Multiple buttons in the child component with the methods in the parent component

Time:12-23

I have a component with two buttons, each with an unique function:

<template>
    <v-container>
        <v - button ref = "button" / >
        <v - button ref = "buttons" / >
    </v-container>
</template>

How I want to address both buttons in the parent and apply my two functions, I have written in the parent, on them.

<Button @click="refer to the two buttons" />
...
<script>
methodOne(){
    console.log("A")
}
methodTwo() {
    console.log("B")
}
</script>

I just don't know how do that correctly. Short: having multiple buttons in the child component and multiple functions in the parent component who should be triggered when the buttons in the child component are triggered.

CodePudding user response:

you can use Vue $emit function inside a child component. So:

Your child component

<template>
    <div>
        <button @click="$emit('aButttonClick')">Button A</button>
        <button @click="$emit('bButttonClick')">Button B</button>
    </div>
</template>

your parent component

<ButtonComponent @aButttonClick="methodOne" @bButttonClick="methodTwo" />
...
<script>
methodOne(){
    console.log("A")
}
methodTwo() {
    console.log("B")
}
</script>

And you can use emit function inside a function. And you can add additional params to.

See here https://vuejs.org/v2/guide/components.html

  • Related