Vue框架型获取数据的两种常用方式axios/fetch

本文介绍了在Vue框架中使用axios和fetch两种方式获取数据的详细步骤,包括get和post请求。对于axios,讲解了从模拟假数据到跨域请求的实践,而对于fetch,强调了其作为全局变量的特性及使用注意事项,如get请求参数处理和Promise的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种:axios

1.获取模拟假数据(mock-json)----get获取

//先引入axios和V的cdn或是安装对应的模块
//https://www.bootcdn.cn/
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>

//写一个json文件,等下要在配置项中写这个文件的路径
{
    "id": 1,
    "name": "小明"
}

//模板
<body>
    <div id="app">
        <button @click = "getData"> 获取mock数据 </button>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        methods: {
            getData () {
                axios({
                    url: './data/data.json',//上面那个json文件
                   method: 'get'
                })
                .then( res => console.log( res ))
                .catch( error => console.log( error ))
            }
        }
    })
</script>

2.获取后端api(php文件)----get获取

//引入axios和Vue.js的cdn或是安装对应的模块
//https://www.bootcdn.cn/

<body>
    <div id="app">
        <button @click = "getPhp"> 获取后端api </button>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        methods: {
            getPhp () {
                axios({
                    url: 'http://localhost/get.php',//本地php文件
                    params: {//需要进行传值
                        a: 1,
                        b: 2
                    }
                })
                .then( res => console.log( res ))
                .catch( error => console.log( error ))
            }
        }
    })
</script>

3.跨域请求线上数据----get方式

//引入axios和Vue.js的cdn或是安装对应的模块
//https://www.bootcdn.cn/

//卖座案例
<body>
    <div id="app">
        <button @click = "get_online"> 获取线上数据 </button>
    </div>
</body>
<script>
    //跨域请求线上数据
    new Vue({
        el: '#app',
        methods: {
            get_online () {
                axios({
                    url: 'https://m.maizuo.com/gateway',
                    headers: {//请求头
                        'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"154549400038873748996477"}',
                        'X-Host': 'mall.film-ticket.film.list'
                    },
                    params: {//传参
                        cityId: 330100,
                        pageNum: 1,
                        pageSize: 10,
                        type: 1,
                        k: 1155271
                    }
                })
                .then( res => console.log( res ))
                .catch( error => console.log( error ))
            }
        }
    })
</script>

4.axios使用post方式请求数据

axios使用post请求数据的步骤
  • 1.先设置请求头
//统一设置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  • 2.实例化 URLSearchParams的构造器函数得到params对象
  • 3.使用params对象身上的append方法进行数据的传参
//引入axios和Vue.js的cdn或是安装对应的模块
//https://www.bootcdn.cn/

<body>
    <div id="app">
        <button @click = "postData"> axios--post请求数据 </button>
    </div>
</body>
<script>
new Vue({
        el: '#app',
        methods: {
            postData() {
                var params = new URLSearchParams() //得到params对象,用来接收参数
                // params.append( key, value )  key就是参数名,value就是参数值
                params.append( 'a', 2 )
                params.append( 'b', 2 )
                axios({
                    url: 'http://localhost/post.php',
                    method: 'post',
                    header: {
                        'Content-Type': "application/x-www-form-urlencoded" //请求头设置为表单提交的请求头
                    },
                    data: params
                })
                .then( res => console.log( res ))
                .catch( error => console.log( error ))
            }
        }
    })
</script>

第二种:fetch(get/post)

fetch是原生javascript提供的 , 所以它 可以当做全局变量使用 ,它是挂载在window对象身上的
//引入Vue.js的cdn或是安装Vue的模块
//https://www.bootcdn.cn/

<body>
    <div id="app">
        <button @click = "getData"> get </button>
        <button @click = "postData"> post </button>
    </div>
</body>
<script>
    new Vue({
        el: '#app',
        methods: {
            getData () {
                fetch( './data/data.json' )
                .then( res => res.json())//对数据进行格式化
                .then( res => console.log( res ))
                .catch( error => console.log( error ))
            },
            postData () {
                fetch( 'http://localhost/post.php', {
                    method: 'post',
                    headers: new Headers({
                        'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
                    }),
                    body: new URLSearchParams( [ ["a",2],["b",2] ] ).toString()
                })
                .then( res => res.text())
                .then( data => console.log( data ))
                .catch( error => console.log( error ))
            }
        }
    })
</script>

注意事项:
A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将
Object --> String
B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据
格式化处理方式有:

fetch('./data.json')
.then(res=>{
    res.json() //res.text() res.blob()
})
.then( data => console.log(data))
.catch( error => console.log( error ))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值