简体   繁体   中英

How to update the front-end automatically if the back-end API data value changes in Vue.js?

I am parsing a JSON data using axios to consume APIs with Vue.js. There is a field value 10 , after 20 mins it can be updated to become 11 .

I am following this code example: https://jsfiddle.net/jonataswalker/416oz6ga/

 getFollowers() { return new Promise((resolve, reject) => { axios.get('https://api.github.com/users/octocat') .then(response => resolve(response)) .catch(err => reject(error)) }); }

Similar to the followers in the above example I want my value to change automatically in my front-end.

How can I update this value in the front-end? Any suggestions?

So, you have two ways you can do this.

One is to use websockets, which is a bidirectional connection from the client to your server. This requires specific configuration on your server, and you'd have to update your client code to handle the data push. A recent Medium post might be a good way for you to get started.

The other method is to use polling on the client. Use a timer such that for every N seconds, it makes a request to the API and updates with the response.

A good breakdown has already been written about the pros and cons of either.

you have no need to return a new promise because if this is in "methods", I'm not sure how you would treat this promise, but axios itself already returns a promise in your query, what you need to do is:

getFollowers() {
  axios.get('https://api.github.com/users/octocat')
  .then(response => this.$set(this, 'data', response.data))
  .catch(err => (throw error))
 }

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