Search code examples
javascriptlaravel-5vue.jslaravel-5.3vuejs2

How to add condition in method vue.js 2?


My code is like this :

<template>
    <a href="javascript:" class="btn btn-block btn-success" @click="addFavoriteStore($event)">
        <span class="fa fa-heart"></span>&nbsp;<label id="favoriteId">{{ store_id == $store->id ? 'Un-Favorite' : 'Favorite' }}</label>
    </a>
</template>

<script>
    export default{
        props:['idStore'],
        mounted(){
            this.checkFavoriteStore()
        }, 
        methods:{
            addFavoriteStore(event){
                var label = $('#favoriteId');
                var text = label.text();

                event.target.disabled = true
                const payload= {id_store: this.idStore}

                if(text == "Favorite") {
                    this.$store.dispatch('addFavoriteStore', payload)
                }
                else {
                    this.$store.dispatch('deleteFavoriteStore', payload)                        
                }

                setTimeout(function () {
                    location.reload(true)
                }, 1500);
            },
            checkFavoriteStore(){
                const payload= {id_store: this.idStore}
                this.$store.dispatch('checkFavoriteStore', payload)
                // this is response. return store_id
            }
        },
        data: {
            store_id: ''
        }
    }
</script>

I make the conditions as described above

You can look at the method addFavoriteStore

Whether that step is correct?

And how to determine it was favorite label or not to create conditions?

UPDATE

In console exist error like this :

[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. 

Solution

  • As error says, when you are dealing with the components, data should be defined as function that return an object - so:

    data() {
      return {
       store_id: ''
      }
    }