Search code examples
javascriptvue.jsvuejs2axios

Vue 2 + Axios - Show / Hide div as result of Axois request result


I have a div in my html page

<div class="ui-alert" v-show="isCaptchaError"> ... </div>

isCaptchaError - initialized in my Vue instance:

const form = new Vue({
    el: '#main-form',
    data: {
        isCaptchaError: false,
    },

In watcher on my input I'm creating axios request and set this.isCaptchaError = true

const form = new Vue({
    el: '#main-form',
...
    watch: {
        phoneNumber(val) {
                        axios({
                            method: 'post',
                            url: '/rest/client',
                            data: ajaxRequest
                        }).then(function (response) {
                            this.isCaptchaError = true;
                        })
        }
    }

But div is not show. If I set this.isCaptchaError = true on any button click then div shows

How to hide / show div after result of axios request?


Solution

  • Give a try to the following

    async phoneNumber(val) {
      const response = await axios({
        method: 'post',
        url: '/rest/client',
        data: ajaxRequest
      })
      this.isCaptchaError = true
    }
    

    Not sure what is your val or your response doing in your snippet of code but this would work well. Feel free to edit with more details/errors if you still have some issues with this.

    This docs' page is still very relevant and useful.