ホーム > Vue > Basic way to write Vue's axios get and post
Vue

Basic way to write Vue's axios get and post

Thank you for your continued support.
This article contains advertisements that help fund our operations.

First of all, the purpose of this article is that while there are many articles on Vue and axios in the world, I wanted to write about the simplest example among them in an easy-to-understand manner.

I will introduce the most commonly seen format among various ways of writing.

Basic way to write GET

The way GET is written is like this.

.vue file

<template>
  <div>
    <div v-for="post in posts">
      <p>{{post.title}}</p>
      <p>{{post.content}}</p>
    </div>
  </div>
  <template>
    <script>
      export default {
        data() {
          return {
            posts: [],
          }
        },
        created() {
          this.test()
        },
        methods: {
          test: function () {
            axios
              .get("/test")
              .then(res => {
                console.log(res)
                this.posts = res.data.posts
              })
              .catch(err => {
                console.log(err)
              })
          },
        },
      }
    </script></template
  ></template
>

Basic way to write POST

<template>
  <div>
    <input v-model="title" />
    <textarea v-model="content"></textarea>
    <button type="button" @click="test">Submit</button>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        title: "",
        content: "",
      }
    },
    methods: {
      test: function () {
        axios
          .post("/test", {
            title: this.title,
            content: this.title,
          })
          .then(res => {
            console.log(res)
            this.posts = res.data.posts
          })
          .catch(err => {
            console.log(err)
          })
      },
    },
  }
</script>

Explanation of GET

GET is mainly used for data retrieval.

    test: function(){
      axios.get('/test').then(res=>{
        console.log(res)
        this.posts = res.data.posts
      }).catch(err=>{
        console.log(err)
      })
    }

In this code,

axios.get('/test')

This line is requesting data from the URL provided.

.then(res=>{
console.log(res)
this.posts = res.data.posts
})

Inside the .then, we write the successful result of the request for data.

In this case, we are checking what was returned.

console.log and assigning the returned posts data to Vue's data.

.catch(err=>{
        console.log(err)
      })

.catch represents the case where the request for data fails. There are different ways to handle this, but we will skip it for now.

This completes the basic axios get function.

However, just defining a function is not enough, it needs to be triggered.

  created() {
    this.test()
  }

In this part, we are triggering the function we created when the component is called. created() is a function that is activated when the component is called. You can also write directly inside this function, but in this case,

this.test()

is written to call the defined function.

  data(){
    return {
      posts: []
    }
  }

In this part, we define the data used in this component and set the initial value.

If this is not done, even if the data request is successful, there is no place to receive the data, resulting in an error.

Here, an empty array is set as the initial value.

<template>
  <div>
    <div v-for="post in posts">
      <p>{{post.title}}</p>
      <p>{{post.content}}</p>
    </div>
  </div>
<template>

This is the display part. The v-for loop displays the content for each item in the array.

Explanation of POST

Next, we will create something where when we enter text and press "submit", the data is sent.

 methods: {
    test: function(){
      axios.post('/test',{
        title: this.title,
        content: this.title
      }).then(res=>{
        console.log(res)
        this.posts = res.data.posts
      }).catch(err=>{
        console.log(err)
      })
    }
  }

Let's break it down again and explain.

   axios.post('/test',{
        title: this.title,
        content: this.title
      })

Here, we are sending a post request to the URL /test.

The second argument

{
    title: this.title,
    content: this.title
}

contains the data to be sent.

The key of the object is title and the value on the right side becomes the Value.

When using Laravel, writing $request->title means that the content of this.title is being sent.

As for .then and .catch, it is the same as when doing a GET request.

The structure of the response depends on the API specification, so you will have to continue writing while checking the content in the Console.

 data(){
    return {
      title: '',
      content: ''
    }
  }

Similar to when doing a GET request, we define a place to receive the text content that will be sent.

The initial value is set to an empty text ''.

<template>
  <div>
    <input v-model="title">
    <textarea v-model="content"></textarea>
    <button type="button" @click="test">Submit</button>
  </div>
<template>

For the input and textarea, we use v-model such that the data matches what is defined in data().

Conclusion

We have written the basic way of writing GET and POST requests using Vue's axios as a sample.

It may be difficult at first to get used to it, but I hope this is easy to understand for those who are seeing this for the first time.

If you have any questions about this article, please DM me on Twitter.

That's all.

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!