1.  
  2. 主页
  3.  / 
  4. Vue2 教程
  5.  / 
  6. Vue教程之axios 基本使用

Vue教程之axios 基本使用

axios是基于promise的http库,可以用在浏览器和node.js中。

promise是ES6中的语法,是用来解决异步编程的。

基本使用

public/data.json

{
  "title": "title",
  "content": "content"
}

src/view/demo/demo1.vue

<template>
  <div>
    <h1>Demo1</h1>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  created () {
    // axios 别名方法方式,发送get请求
    axios.get('/data.json').then(response => {
      console.log(response)
    }).catch(err => {
      console.log(err.message)
    })

    // axios 方式发送get请求
    axios({
      url: '/data.json',
      method: 'get'
    }).then(resp => {
      console.log(resp)
    }).catch(err => {
      console.log(err)
    })
  }
}
</script>

常用的HTTP请求方法

在详细讲解 axios 的时候,我们先了解下平时开发中,常用到 HTTP 请求方法。

同时基于 RESTFUL API 的规范来看下,每种 HTTP 请求,都是对应的什么功能。

  • GET :读取资源
  • POST :新建资源
  • PUT :全量更新资源
  • PATCH :增量更新资源
  • DELETE :删除资源

例如:

  • GET /article/:id 读取一篇文章
  • POST /article 新建文章
  • PUT /article/:id 更新全文
  • PATCH /article/:id 更新部分内容
  • DELETE /article/:id 删除一篇文章

axios 别名

  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.put(url[, data[, config]])
  • axios.post(url[, data[, config]])
  • axios.patch(url[, data[, config]])

实例演示

get

<script>
import axios from 'axios'
export default {
  methods: {
    handleGet () {
      axios.get('/data.json', {
        params: {
          id: 1234
        }
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

delete

<script>
import axios from 'axios'
export default {
  methods: {
    handleGet () {
      axios.delete('/data.json', {
        params: {
          id: 1234
        }
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

post

<script>
import axios from 'axios'
export default {
  methods: {
    handleGet () {
      axios.post('/data.json', {
        data: {
          id: 1234
        }
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

put

<script>
import axios from 'axios'
export default {
  methods: {
    handleGet () {
      axios.put('/data.json', {
        data: {
          id: 1234
        }
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

patch

<script>
import axios from 'axios'
export default {
  methods: {
    handleGet () {
      axios.patch('/data.json', {
        data: {
          id: 1234
        }
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

这篇文章对您有用吗?

我们要如何帮助您?

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注