Why is this lifecycle hook code working twice?

∥☆過路亽.° 提交于 2021-01-29 09:31:36

问题


There is such a code:

<template>

   <div class="wrapper">
   </div>

</template>

<script>

import axios from 'axios';

export default{

  created () {
    console.log('222');
    this.getTrackerIdData();
    this.getTrackerData();
  },

  methods: {

    getTrackerIdData () {
        return axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking_new.create" , {
         })
        .then(response => {
          this.$store.commit('tracker/setTrackingKeyId', response.data.data.tracking_new_key_id);
          this.$store.commit('tracker/setQrCodeUrl', response.data.data.filename_qr_code_tracking_new);
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    getTrackerData () {

        setInterval(()=>myTimer(this), 60000);

        function myTimer(th) {
             return axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=get_tracking_data&key_id=" + th.$store.state.tracker.trackingKeyId , {
             })
            .then(response => {
              th.$store.commit('tracker/setTrackingServerData', response.data.data.tracking_data);
            })
            .catch(function (error) {
              console.log(error);
            });
        }

},

  }
}
</script>


When starting such a solution in the project, the server-side developer informed me that at least the request method getTrackerIdData () on its side works twice!
Having placed the code (console.log ('222');) in the hook of the created lifecycle (where the method calls), I found that it is displayed twice in the firebug:


Question:
Why is this happening and what approach is right in this case from the point of view of the implementation of receiving data from the server?

P.S. If everything is called in the mounted hook, then the code works, including on the server side, only 1 time.


回答1:


It is important to know that in any Vue instance lifecycle, only beforeCreate and created hooks are called both from client-side and server-side. All other hooks are called only from the client-side.

so thats why created hook called 2 times and executing the console.log ('222'); twice

for reference you can read from here



来源:https://stackoverflow.com/questions/60199338/why-is-this-lifecycle-hook-code-working-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!