29

vue中数据请求的三种方法

 4 years ago
source link: http://www.cnblogs.com/dcyd/p/12491949.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

注意请求可能存在跨域问题,需要去配置好

这三种建议使用axios

1.resource

Vue 要实现异步加载需要使用到 vue-resource 库。

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

先导入一个线上cdn的地址,当然还可以去npm安装,但个人觉得这种方便

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

实现GET请求

    <div id="box">
        <ul>
            <li v-for='item of img'><img :src='item.img' alt=""></li>
        </ul>
    </div>
    <script>
        var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted() {
                //get请求
                this.$http.get('http://localhost:3000/api/banner').then(function(res){
                    this.img = res.body.data
                },function(){
                    console.log('请求失败处理');
                });
            }
        })
    </script>

如果需要传递数据,可以使用 this.$http.get('get.php',{params : jsonData}) 格式,第二个参数  jsonData 就是传到后端的数据。

实现POST请求

<div id="box">
        <ul>
            <li v-for='item of img'><img :src='item.img' alt=""></li>
        </ul>
    </div>
    <script>
        var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted() {
                //post请求  需要第三个参数{emulateJSON:true}
                this.$http.get('http://localhost:3000/api/banner',{name: '王富贵'},{emulateJSON:true}).then(function(res){
                    this.img = res.body.data
                },function(){
                    console.log('请求失败处理');
                });
            }
        })

post 发送数据到后端,需要第三个参数 {emulateJSON:true}。

emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。

2.fetch(次方法vue自带的不需要安装其他)

GET方法

这个方法只能在地址栏传参

//get方法  只能在地址栏传参
fetch('http://localhost:3000/api/banner')
.then(res => {
    //return 返回给上一层 ,不然下一层用不了
    return res.json()
})
.then(data => {
    console.log(data)
})

POST方法

var url = 'http://localhost:3000/api/user/loging'
fetch(url, {
    method: 'post',
    headers: {
        //这里是需要去network里面看
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'tel=xdd212&password=1515'
})
.then(res => {
    //return 返回给上一层 ,不然下一层用不了
    return res.json()
})
.then(data => {
    console.log(data)
})

另一种传参方式

//post 另一种传参方式
fetch(url, {
    method: 'post',
    headers: {
        //看个人习惯
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        tel: 'xdd212',
        password: '1515'
    })
})
.then(res => {
    //return 返回给上一层 ,不然下一层用不了
    return res.json()
})
.then(data => {
    console.log(data)
})

3.axios

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

用法和jq很类似

安装或者引入cdn地址   npm i axios

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

GET请求

    <div id="box">
        <ul>
            <li v-for='item of img'><img :src='item.img' alt=""></li>
        </ul>
    </div>
    <script>
        var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted(){
                //需要传参的话可以在地址栏后面拼接
                axios.get('http://localhost:3000/api/banner',
                //还可以这样传参
                //     {
                //         params:{
                //             name:'王富贵'
                //         }
                //     }
                )
                .then(res => {
                    console.log(res)
                })
            }
        })
    </script>

POST请求

    <div id="box">
        <ul>
            <li v-for='item of img'><img :src='item.img' alt=""></li>
        </ul>
    </div>
    <script>
        var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted(){
                //需要传参的话可以在地址栏后面拼接
                axios.post('http://localhost:3000/api/urse/loging',
                     {
                            age: 18
                             name:'王富贵'
                     }
                )
                .then(res => {
                    console.log(res)
                })
            }
        })
    </script>

一次执行多个请求

var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted(){
                function fn1(){
                    return axios.get('http://localhost:3000/api/banner')
                }
                function fn2(){
                    return axios.get('http://localhost:3000/api/pro')
                }
                //注意这里必须要使用数组
                axios.all([fn1() , fn2()])
                //函数里面对应的数字里面的值
                .then(axios.spread(function (fn1, fn2) {
                    console.log(fn1)
                }))
            }
        })

axios

可以自己配置参数

var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted(){
                axios({
                    //注意不写请求方式的话默认是get
                    method: 'post',
                    url: 'http://localhost:3000/api/user/loging',
                    data: {
                        tel: "xdd212",
                        password: "1515"
                    }
                })
                .then(res => {
                    console.log(res)
                })
            }
        })

你可以自己定义一个axios

        //这里创建一个自定义配置的axios
        var init = axios.create({
            //这里可配置文件的长路径
            baseURL: 'http://localhost:3000/api'
        })
        // 假设如果很多接口都需要使用 token验证,可以把token信息放在请求头
        init.defaults.headers.token = '1231654984561646546565464654654646321654asdasdasd'

        var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted(){
                //下面调用axios的时候就是调用我们自定义创建的
                init({
                    method:'get',
                    //然后到这下面可以直接写短路径,后期方便维护
                    url: '/banner'
                })
                .then(res => {
                    console.log(res)
                })

                //此方法也是一样
                init.get('/banner')
                .then(res => {
                    console.log(res)
                })
            }
        })

拦截器

请求拦截器和响应拦截器

//请求前
        axios.interceptors.request.use(function (config) {
            // 可以设置 加载的动画效果 的展示
            //这里指的是请求之前做点什么
            console.log('正在加载...')
            return config
        }, function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        })

        //响应前
        axios.interceptors.response.use(function (config) {
            // 可以设置 加载的动画效果 的隐藏
            //这里指的是请求之前做点什么
            console.log('加载完毕')
            return config
        }, function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        })

        var app = new Vue({
            el: '#box',
            data: {
                img: ''
            },
            mounted(){
                axios.get('http://localhost:3000/api/banner')
            }
        })

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK