Waiting for Requests and User Input: A Guide to Patient Expectations
P粉368878176
P粉368878176 2024-02-26 13:25:04
0
1
333

Suppose I make an asynchronous request when the component loads. The component also has a submit button that the user can press to trigger a function that depends on the result of the original request. How can I delay the execution of a triggered function until the async request completes?

If this doesn't make sense, let me give you an example. MyComponent Makes an asynchronous request getRandomColor() on mounted. The template of MyComponent has <button @click="handleClick">. handleClick Call some functions saveColor(). How do I ensure that saveColor() is not called before the async getRandomColor() completes?

I'm currently using Vue.js, but I think this question applies to all javascript.

P粉368878176
P粉368878176

reply all(1)
P粉329425839

You can achieve this by adding the :disabled attribute to the button element. The value of :disabled will be based on the response. That is, if there is a response, enable it, otherwise disable it.

Working Demonstration:

const app = Vue.createApp({
  el: '#app',
  data() {
    return {
        buttonText: 'Call Me!',
      apiResponse: [],
      isDisabled: false
    }
  },
  methods: {
    saveColor() {
        console.log('saveColor method call');
    }
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
      this.apiResponse = response.data; // Here we are getting proper response. hence, button is getting enabled.
    }).catch((error) => {
        console.warn('API error');
        });
  }
})
app.mount('#app')



Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!