Vue数据请求方式有两大种:

1、第三方提供的数据请求库:axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

2、原生JS提供的请求方式:fetch


一、axios数据请求方式

1、使用axios请求模拟数据

2、使用axios进行get数据请求

3、使用axios进行post数据请求

下面按照顺序来学习下用法

先在官网中引入文件

vue axios 请求指定返回类型 vue数据请求axios_vue axios 请求指定返回类型

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

1、使用axios请求模拟数据

第一种写法:axios.get(url).then(res).catch(err)
第二种写法:axios(url,get).then(res).catch(err)

methods: {
            // 第一种写法:axios.get().then().catch()
            getMock() {
                //     axios.get('./mock/data.json')
                //     .then(res => console.log( res )) 
                //     .catch(err => console.log( err ))
                // 

                // 第二种写法:axios().then().catch()
                axios({
                    url: './mock/data.json',
                    method: 'get'
                })
                    .then(res => console.log(res))
                    .catch(err => console.log(err))
            }
        }
    })

2、使用axios进行get数据请求

写法:axios.get(url,{options}).then().catch()
这里的提供了一种axios简写

const ins = axios.create({
       baseURL: 'http://59.110.226.77:3000' //统一把域名放在这个全局变量中
   })
get () {
        // 进行get请求
        // axios.get(url,options).then().catch() 
        ins.get('/api/list/hot',{  //这里的写成这样了  因为统一简写了,没全局变量的域名时,写axios.get
          // params表示请求携带参数
          params: {
            cid: 22    //到时候参数会自动接上去?cid=22在网址后
          }
        }).then(res => console.log( res ))
          .catch(err => console.log( err ))
      }

3、使用axios进行post数据请求

第一种提交json数据时:这里的input都是用v-model绑定

//注册提交时 非表格类型 只是输入框和提交按钮
 postJson () {
        // 进行post json提交类型   Content-Type: application/json
        // 参数类型   request payload   是一个对象
        // axios.post(url,data,option).then().catch()
        ins.post('/api/user/register',{
          username: this.username,
          phone: this.phone,
          password: this.password
        }).then(res => console.log( res ))
          .catch(err => console.log( err ))
      }

第二种:提交表格数据时:这里的表单都是用v-model绑定

postForm () {
        // 进行post  表单提交类型  Content-Type: application:x-www-form-urlencoded
        // 参数类型:  Form Data
        // 需要对参数做一个处理,做一个转换
        const params = new URLSearchParams()
        params.append('username',this.user)//这里的user就是v-model绑定的user变量
        params.append('password',this.pass)
        instance.post('/api/user/login',params,{
          headers: {
            // 设置请求头
            'Content-Type': 'application/x-www-form-urlencoded'
            //注意设置这个请求头
          }
        }).then(res => console.log(res))
          .catch(err => console.log(err))
      }

这三种请求方式一定要熟练掌握


2、原生JS提供的请求方式:fetch

1、使用axios请求模拟数据
写法:fetch(url,options).then().then.catch(),两个then()

getMock() {
               //模拟数据请求
               // 写法:fetch(url,options).then().then.catch(),两个then()
               //第一个then表示请求到的数据进行格式化
               // 第二个then可以获得格式化后的数据
               fetch('./mock/data.json')
                   .then(data => data.json())//将得到json数据
                   .then(res => console.log(res))
                   .catch(err => console.log(err))
           }

2、使用axios进行get数据请求

get() {
                //进行get请求
                //get请求参数需要连接在url后面
                fetch('http://59.110.226.77:3000/api/user/getInfo?userId=5e980ee6771cdf43999456b1&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Inl5YiIsInBhc3N3b3JkIjoieXliMTIzIiwiY3RpbWUiOjE1ODIyODk0MjU2NTQsImlhdCI6MTU4MjI4OTQyNX0.-2pV6kR39zsWyPoViM9vhZxxOGNs-uzKj5GFL6JYkWA')
                    .then(data => data.json())
                    .then(res => console.log(res))
                    .catch(err => console.log(err))
            }

3、使用axios进行post数据请求

进行json数据提交

postJson() {
                //进行json提交
                fetch('http://59.110.226.77:3000/api/user/register', {
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    methods: 'POST',
                    body: JSON.stringify({ //将json格式变成原生js
                        username: this.username,
                        phone: this.phone,
                        password: this.password
                    })
                })
                .then(data => data.json())
                .then(res => console.log(res))
                .catch(err => console.log(err))
            }

进行表单提交

postForm(){
                // 进行表单提交
                fetch('http://59.110.226.77:3000/api/user/login',{
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    // 参数是一个二维数组
                    body: new URLSearchParams([['username',this.user],['password',this.pass]])
                })
                .then(data => data.json())
                .then(res => console.log(res))
                .catch(err => console.log(err))
            }