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
        })
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM