0

So I have a Vue2 app. I have create a component "u-button"

when i import this and use it in another component, I want to be able to add a click function to it. However at the moment it looks for a function on the u-button component rather than the component it is being used in.

so for example, in the below if i click the first button nothing happens, if i click the second button i get the console log.

<template>
    <div>
        <u_button @click="clicked">Click me</u_button>
        <button @click="clicked">Click me</button>
    </div>
</template>

<script>
    import u_button from '../components/unify/u_button'

    export default {
        components: {
            u_button
        },
        methods: {
            clicked() {
                console.log("Working!");
            }
        }
    }

</script>

However if i add a method on the u-button component, then it calls that. So how can i get my below example to work ? The only thing I can think of is to wrap it in another div and add the click function to that. but I'm wondering if there is a better way?? I dont want to use events to do this either as that gets messy very quickly.

As you can imagine having a reusable button that when clicked always performs the same function is a bit pointless.

2

1 Answer 1

4

It's because of the nature of components for example if we had a (virtual) iframe component which had a button in it and we'd like to detect click event on it we might name the event click and listen for it in the parent component; therefore, Vue introduced a feature called event modifiers for example in Vue, We have .native modifier (you can read more about the Vue modifiers here)

Now, to make your code work, You should add a .native after @click like this:

<u_button @click.native="clicked">Click me</u_button>

By the way, it's better to develop a naming convention for yourself It'd become handy when your projects get larger.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.