1. 程式人生 > 實用技巧 >vue請求api

vue請求api

axios

axios可以在vue應用中訪問一個 API 並展示其資料,是封裝的ajax。

在使用axios前,需要先引入axios.js

使用axios獲取資訊

使用axios的get方法請求api並獲取資料

<script type="text/javascript">
    // 全域性axios
    Vue.prototype.$axios = axios
    var vm = new Vue({
        el:'#app',
        data:{
            list:[]
            },
        methods:{
            getProduct(){
                // 使用axios-get方法獲取資料
                this.$axios.get('https://www.yiqigoumall.com/index/items/is_best')
                .then((res) => {
                    console.log(res.data.data)
                    this.list = res.data.data
                    })
                .catch(err => {
                    console.log(err)
                })
            }
        },
        created(){
            this.getProduct()
        }
})
</script>

使用axios向api傳送資訊

使用axios向api傳送資訊的方法如下:

methods:{
    // post
    postAddress(){
        this.$axios({
            method:"post",
            url:'https://www.yiqigoumall.com/address/createOrUpdate',
            params:{
                addressId:''
                },
                headers:{
                    "contentType":"application/json;charset=UTF-8"
                },
                data:{
                    userId:'67575555555553',
                },
                dataType:"json"
            })
            .then(res => {
                console.log(res.data)
                })
            .catch(err => {
                console.log(err)
                })
            }
        }
    }
}

fetch

fetch 是JS ES6中新增的一種新的方法,fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest物件。

下面是使用fetch請求api的方法

使用fetch無需引入新的js庫,因為他是原生js方法。

methods:{
    getProduct(){
        fetch('https://www.yiqigoumall.com/index/items/is_best')
        .then(result => result.json())
        .then(res => {
            console.log(res.data)
            this.list = res.data
        })
    }
}