1

I am creating a shopping cart type button to count the number of times clicked, the button should call a function when clicked with the parameter of the id, however, it won't call the function with the correct parameter

I have tried adding {{id}} and :onClick="addThisToCart({{id}} but getting a ton of errors.

Heres my code

        Vue.component('movietable', {
            props: ['title', 'price', 'mid'],
            template: `
                <tr>
                    <td>{{title}}</td>
                    <td>{{price}}</td>
                    <td>
                    <div class="quantity">
                        <button onClick="addThisToCart({{mid}}">You clicked me {{ count }} times.</button>
                    </div>
                    </td>
                </tr>
                `,
            data: function () {
                return {
                    count: 0
                }
            },
        });

mid is being defined in the properties section of the vue element and then the function

var cart = 0;
        function addThisToCart(movieId) {
            var movieId = this.mid;
            this.cart += 1;
            this.cart += 1;
            console.log(movieId);
            console.log(cart);
        }

It should add +1 to cart every time the button is clicked, however, getting a ton of errors and instead of sending '4434' it is sending {{mid}}

1 Answer 1

3

You can use

<button @click="addThisToCart(mid)">You clicked me {{ count }} times.</button>

No curly braces for the argument of the function.

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

4 Comments

isn't working, nothing happens after I even checked console with a console.log in the function, nothing
codepen.io/Smixi/pen/BezZbr for demo (updated because wrong link)
Sorry that's not quite what I'm wanting so let me explain, I have a javascript page writing Dynamic HTML into vue component, getting the information from an online API, the API should send the ID to the HTML page and add it to the button, it's working except when I try to call the cart function and add 1 to the cart when it is clicked, I just need it to send the ID instead of the word 'mid' which it is sending now.
@KolemanPa I'm little confused with the code on your github, you defined multiple time the component movietable. Also, your function addThisToCart() doesn't use the movieId parameters, as you create a new variable. Note that i'm unsure about which object this refers in the context (i'm used to typescript vuejs, so it usually refer to the component).

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.