javascript - How can i show and hide a bootstrap spinner with Vue.js? - Stack Overflow

<button type="button" class="btn btn-primary" data-bs-toggle="modal" d

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" v-on:click="api">
  ...
</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  ...
</div>

I want to show the spinner on the button when I click it.

When the api returns the result, then pop up the modal and hide the spinner at the same time.

It seems relatively easy to implement with jQuery, and as a beginner in vue.js, I was at a loss when writing this code

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" v-on:click="api">
  ...
</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  ...
</div>

I want to show the spinner on the button when I click it.

When the api returns the result, then pop up the modal and hide the spinner at the same time.

It seems relatively easy to implement with jQuery, and as a beginner in vue.js, I was at a loss when writing this code

Share Improve this question asked Apr 11, 2021 at 5:15 neuron42neuron42 451 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

This is easy with v-show. This allows you to bind to a variable and control if a tag should be visible or not. If the variable is truthy then the element is shown, if it is falsy then the element is hidden. You can learn more about v-show from the docs.

So in your button we need to create a tag to wrap the button text. In this case we will use <span>. Then we will create a spinner with pure bootstrap with:

<div v-show="loading" class="spinner-border spinner-border-sm" role="status">
    <span class="sr-only">Loading...</span>
</div>

Now we create your button

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" v-on:click="API">
      <span v-show="!loading"> Button Text  </span>
      <!-- IF YOU ARE USING VUE BOOTSTRAP USE <b-spinner label="Loading..."></b-spinner> -->
      <div v-show="loading" class="spinner-border spinner-border-sm" role="status">
          <span class="sr-only">Loading...</span>
      </div>
</button>

Next in your code, you need to create a loading variable

data(){
  return{ 
     ...
     loading:false,
     ...
  }
}

Then when you are handling your request you need to control the loading variable.

methods:{
  API(){
    this.loading = true;
    axios.get("/test").then(({res})=>{
        this.loading=false;
    }).catch((error)=>{
        console.log(error);
        this.loading=false;
    });
  }
}

Code SandBox example

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745150714a4613855.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信