J1MAV1GN0N
J1MAV1GN0N

Reputation: 33

Vue.js - How to load data with method call via click and toggle data?

I'm loading data via my rest api when the button is clicked with a vue.js method. To hide the loaded data I'm clicking the button again. When I'm clicking the button to show the data again, the same method is called again and the data is shown twice.

<div v-if="comment.answers_count !== 0">
            <button
                    @click="toggleAnswers"
                    :class="{
                    'btn-danger': loadAnswers,
                    'btn-outline-danger': !loadAnswers
                    }"><strong>{{ comment.answers_count }} show answers</strong></button>
</div>

How can I load the data once, hide it with button clicked and show the same loaded data when toggling the button?

Maybe theres a way to use a computed property?

Upvotes: 1

Views: 1860

Answers (2)

Swordword
Swordword

Reputation: 171

So,i can't get you real purpose? if you want to just load data once, you can use v-once, eg

<button @click.once="loadData" @click="hideData"> loadData or hideData</button>
... 
loadData() {
      setTimeout(() => {
        this.data = 'loaded data'
      }, 500)
    },
hideData() {
      this.data = this.data && null
}

if you want the toggle circle then you should set a tag using %2 to judge which function to run .

Upvotes: 0

gijoe
gijoe

Reputation: 1189

Create a new property in data:function(){} e.x

data:function(){
  answers_loaded:false
}

then on your function toggleAnswers do the following

methods:{
    toggleAnswers:function(){
       /** if answers are not loaded , load them **/
       if(!this.answers_loaded){
           /** mark answers_loaded to true, so we do not call this code
           again. Should be better put on your success request handler
           to make sure that they were successfully loaded**/
           this.answers_loaded = true;
           
           //code to load the answers

       }
    }
}

So the first time that you click the button and function toggleAnswers is called the variable answers_loaded pass the if check.

Every other time that you click the button since answers_loaded is equal to true, it will fail the if check and wont call again part of the code to load the answers

Upvotes: 1

Related Questions