我试图在api调用成功时显示div。当我单击按钮并完成过程时,请使用v-if控件检测变量为true或false。

     <div id="app" class="container h-100">

        <div v-if="correct==true" class="alert alert-success" role="alert">
             <strong>Correcto</strong>. Datos actualizados de forma satisfactoria.
        </div>

        <button v-on:click="guardar" type="button" class="btn btn-outline-primary btn-block">Modificar </button></div>

</div>

            <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
            <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
            <script>
                var app = new Vue({
                    el: '#app',
                    data() {
                        return {
                            correct: false
                        }
                    },
                    methods: {
                        guardar: function () {
                            axios
                                .get('ENDPOINT')
                                .then(response => {
                                    return {
                                        correct: true
                                    }
                                })
                                .catch(function (error) {
                                    console.log(error);
                                })
                        },
                    }
                })
            </script>


问题:V-if无法检测到“正确”变量何时为真。我想我得到回应时出了点问题。完成过程后将“正确”变量设置为true的正确方法是什么?

最佳答案

成功获取请求后,您应该更改状态

<div v-if="correct" class="alert alert-success" role="alert">
      <strong>Correcto</strong>. Datos actualizados de forma satisfactoria.
</div>

methods: {
  guardar: function () {
     axios
         .get('ENDPOINT')
         .then(response => {
            // here update the correct state
            this.correct = true
          })
          .catch(function (error) {
             console.log(error)
             this.correct = false
          })
     }
 }

09-25 18:36