【转】[Vue] 常见的几种 axios 写法

<template>
    <div>
        <h1> User Data</h1>
        <input type="button" value="获取远程数据" @click="sendPost4()">
    </div>
</template>

<script>
    import axios from 'axios';

    const options = {
        data: function(){
            return {
                users: []
            };
        },
        methods : {
            // 用 get 方法获取数据,不带请求体,不带 headers 头信息
            async sendReq() {
                const resp = await axios.get('/api/users');
                console.log(resp);
            },
            // 用请求体发数据,格式为 json,带 headers 头信息

            async sendPost(){
                const resp = await axios.post('/api/users', {name: 'zhangsan'},{
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: 'Bearer token 2'
                    }
                });
                console.log(resp);
            },            
            async sendPost2(){
                const resp = await axios.post(`/api/users?name=${encodeURIComponent('张三')}&age=18`);
                console.log(resp);
            },
            // 与 sendPost2 效果相同,更建议这种写法
            async sendPost3(){
                const resp = await axios.post('/api/users',{},{
                    params: {
                        name: '张三',
                        age: 18
                    }
                });
                console.log(resp);
            },
            // 用请求体发数据,格式为 urlencoded
            async sendPost4(){
                const params = new URLSearchParams();
                params.append('name', '张三');
                params.append('age', 18);
                const resp = await axios.post('/api/users',params);
                console.log(resp);
            },
            // 用请求体发数据,格式为 multipart
            async sendPost5(){
                const params = new FormData();
                params.append('name', '张三');
                params.append('age', 18);
                const resp = await axios.post('/api/users',params);
                console.log(resp);
            }
        }

    };

    export default options;
</script>

 

posted on 2025-01-27 10:01  z5337  阅读(19)  评论(1)    收藏  举报