简体   繁体   中英

How to instant data refresh with Laravel and vue.js?

I work with constantly changing api data. I use Laravel and Vue.js. There is a steady stream of data when I control the network with F11. But it has no effect on the DOM.

Here are sample codes. I would be glad if you help.

HTML code;

    <div class="row">
         <div class="col-md-12">
               <p class="tv-value" v-html="totalMeetings"></p>
          </div>
    </div>

Script Code;

    <script>
        export default {
            data() {
                return {
                    totalMeetings: null
                }
            },

            created() {
                this.getPosts();
            },

            methods: {
                getPosts() {
                    axios
                        .get("/get-total-meetings")
                        .then(response => (this.totalMeetings = response.data))
                        .catch(error => {
                            this.errors.push(error);
                        });
                }
            },

            mounted() {
                setInterval(function () {
                    axios
                        .get("/get-total-meetings")
                        .then(response => (this.totalMeetings = response.data))
                        .catch(error => {
                            this.errors.push(error);
                        });
                }, 2000)
            }
        }
    </script>

Change your setInterval function to arrow function like this.

setInterval(() => {
       axios
            .get("/get-total-meetings")
            .then(response => (this.totalMeetings = response.data))
            .catch(error => {
            this.errors.push(error);
        });
}, 2000);

You could put a watcher for that to be able vue to watch the changes of your data. like this.

watch: {
  totalMeetings(val) {
       this.totalMeetings = val
  }
}

Or create a computed property for it to update the value when it changes.

computed: {
    total_meetings() {
       return this.totalMeetings
    }
}

then your component should look like this

<p class="tv-value" v-html="total_meetings"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM