Search code examples
javascriptlaravelvue.jslaravel-5.3vuejs2

How to display button link with vue.js?


My view is like this :

<div class="panel panel-default panel-store-info">
    ...
    <div id="app">
        <AddFavoriteProduct></AddFavoriteProduct>
    </div>
    ....
</div>

My component is like this :

<template>
    <a href="javascript:" class="btn btn-block btn-success" @click="addFavoriteProduct({{ $product->id }})">
        <span class="fa fa-heart"></span>&nbsp;Favorite
    </a>
</template>

<script>
    export default{
        name: 'AddFavoriteProduct',
        props:['idProduct'],
        methods:{
            addFavoriteProduct(event){
                event.target.disabled = true
                const payload= {id_product: this.idProduct}
                this.$store.dispatch('addFavoriteProduct', payload)
                setTimeout(function () {
                    location.reload(true)
                }, 1500);
            }
        }
    }
</script>

When click button favorite, it will call controller on the laravel

I had register on the app.js like this :

...
import AddFavoriteProduct from './components/AddFavoriteProduct.vue';
...
components: {
                ...
                AddFavoriteProduct
            },
...

When executed, the button favorite does not appear.

Please help.

UPDATE

There exist error like this :

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option. (found in root instance)

Whereas I had register it


Solution

  • Three fixes that I can see...

    First, omit name: 'AddFavoriteProduct' in your component (it's not required for single-file components) and use kebab-case for the component in your template. Second, you appear to be missing the id-product prop

    <add-favorite-product :id-product="someProductIdFromSomewhere"></<add-favorite-product>
    

    Third, you don't use interpolation in bound properties and you don't even need to pass anything other than the $event to your addFavoriteProduct method

    @click="addFavoriteProduct($event)"