moses toh
moses toh

Reputation: 13192

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. 

Upvotes: 0

Views: 2938

Answers (2)

Simon Davies
Simon Davies

Reputation: 3686

your data should be set as:

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

As its a component? Try this?

Upvotes: 1

Belmin Bedak
Belmin Bedak

Reputation: 9201

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: ''
  }
}

Upvotes: 3

Related Questions