Search code examples
vue.jsvuejs2vue-componentvue-resource

How to add preloader and success message on form submit using vue-resource


How to accomplish below task using vue-resource:

  1. Include preloader text Loading... or gif image when fetching the data from the server.
  2. Show success message on form submit.

Solution

  • One way of doing this is :

    <template>
    
        <div>
            <div class="loader" v-if="loader"></div>
            <div>
                //display fetchedData using logic you wish like v-for.....
            </div>
            <form>
                //your form inputs
                <button @click.prevent="submit">Submit</button>
            </form>
        </div>    
    
    </template>
    
    <script>
    
    
        export default{
            data(){
                return{
                    loader: false,
                    fetchedData: null
                }
            },
            mounted(){
                this.loader = true;
                    this.$httpget('your_url')
                        .then(response => {
                            this.fetchedData = response;
                            this.loader = false;
                        },err => {
                        });
            },
            methods:{
    
                submit(){
                    this.loader = true;
                    this.$http.post('your_url', {your_body})
                        .then(response => {
                            this.loader = false;
                        },err => {
                            alert('form not submitted');
                        });
                }
            },
    
        }
    </script>
    
    <style scoped>
        loader {
            position: absolute;
            left:50%;
            top:50%;
            transform: translate(-50%, -50%);
            border: 10px solid #f3f3f3; /* Light grey */
            border-top: 16px solid #3498db; /* Blue */
            border-radius: 50%;
            width: 75px;
            height: 75px;
            animation: spin 2s linear infinite;
        }
    
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style> 
    

    Here is the working fiddle