[Vuejs]-How to trigger http requests from Vue.js?

4๐Ÿ‘

A good way to make HTTP requests via VueJS is to use Axios. They provide easy to use methods and have a good amount of documentation to do so. Here is an example for how to set up Axios and make a simple HTTP GET request. Also, here is documentation on how responses are formatted by Axios when you make an HTTP request.

1๐Ÿ‘

Add axios lib to your project and try this ๐Ÿ˜‰

 <div id="app">
  <div v-if="loading">
    loading...
  </div>
  <div v-else>
    <ul>
      <li v-for="post in posts">
        <h1>
          {{post.title}}
        </h1>
        <p>
          {{post.body}}
        </p>
      </li>
    </ul>
  </div>
</div>



const URL = 'https://jsonplaceholder.typicode.com/posts';
new Vue({
    el: '#app',
    data() {
    return {
        loading: true,
      posts: [] // add posts here so reactivity is working, also undefined would be OK
    }
  },
  created() {
    //this.loading = true --> not needed already set in data
    axios.get(URL).then((response) => {
        // console.log(response.data, this)
      this.posts = response.data
      this.loading = false
    })
  }
})

Leave a comment