How to use ajax in vuejs

青灯夜游
Release: 2023-01-11 09:21:48
Original
3416 people have browsed it

Method: 1. Install and introduce axios, and use "axios([option])", "axios.get(url[,...])" and other methods to send requests. 2. Install and introduce vue-resource, and use "this.$http.jsonp(url,[...])" to send the request.

How to use ajax in vuejs

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

Vue itself does not support sending AJAX requests and needs to be implemented using plug-ins such as vue-resource and axios.

axios is a Promise-based HTTP request client used to send requests. It is also officially recommended by vue2.0. At the same time, vue-resource will no longer be updated and maintained.

How vuejs uses ajax

1. Install axios and introduce

1) npm The way: npm install axios -S

2) The bower way: bower install axios

3) The cdn way: <script src="https://unpkg.%20com/axios/dist/axios.min.js%E2%80%9D></script>

2.%20Basic%20usage

1)%20axios(%5Boptions%20%5D)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>axios发送ajax请求基本用法</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <button @click="send">发送ajax请求</button>
    </div>
    <script>
        new Vue({
            el:"#app",
            methods:{
                send(){
                    axios({
                       method:&#39;get&#39;,
                        url:&#39;user.json&#39;
                    }).then(function(res){
                        console.log(res.data.name);
                    });
                }
            }
        });
    </script>
</body>
</html>
Copy after login

How to use ajax in vuejs
2) axios.get(url[,options]);

Parameter passing method:
(1) Pass through url Parameter axios('url?key=value&key1=val2').then();
(2) Pass parameter axios('url',{params:{key:value}}).then(); through params option

3) axios.post(url,data,[options]);

When axios sends data by default, the data format is Request Payload, not the commonly used Form Data Format,
So the parameters must be passed in the form of key-value pairs, not in json form.

Parameter passing method:

(1) Splice it into key-value pairs yourself

axios.post(‘url’,’key=value&key1=value1’).then();
Copy after login

(2) Use transformRequest to convert the request before sending it Data conversion

axios.post(&#39;url&#39;,data,{
                        transformRequest:[
                                function(data){
                                    let params = &#39;&#39;;
                                    for(let index in data){
                                        params +=index+&#39;=&#39;+data[index]+&#39;&&#39;;
                                    }
                                    return params;
                                }
                        ]
                    }).then(function(res){
                        console.log(res.data)
                    });
Copy after login

(3) If you use modular development, you can use the qs module for conversion

axios itself does not support sending cross-domain requests and does not provide For the corresponding API, the author has no plans to add support for sending cross-domain requests in axios.
So we can only use third-party libraries

Cross-domain requests (using vue- resource to send cross-domain requests)

1. Steps to use vue-resource to send cross-domain requests

  • Install vue-resource and import it :npm install vue-resource -S
  • Basic usage:

Use this.$http.jsonp(url,[ops]) to send a request

2. Basic usage demonstration (360 search)

1) Open 360 search, and then enter the character 'a' and some search options will be automatically prompted, as shown in the figure
How to use ajax in vuejs
2) Copy link
https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
3) Code Demonstration

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用vue-resource发送跨域请求</title>
    <!--引入vue、vue-resource文件-->
    <script src="vue.min.js"></script>
    <script src="vue-resource.min.js"></script>
</head>
<body>
    <div id="app">
        <button @click="sendJsonp">send</button>
    </div>
    <script>
            var vm = new Vue({
                el:"#app",
                methods:{
                    sendJsonp:function(){
                        this.$http.jsonp(&#39;https://sug.so.360.cn/suggest&#39;,{
                            params:{
                                word:&#39;a&#39;
                            }
                        }).then(function(res){
                            console.log(res.data);
                        });
                    }
                }
            });
    </script>
</body>
</html>
Copy after login

4) Results

How to use ajax in vuejsHow to use ajax in vuejs

3. Basic example demonstration (Baidu search)

1) The requirements are the same as those of 360 search

How to use ajax in vuejs
2) Copy link
=1526436420943”>https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json= 1&p=3&sid=1467_21117_20927&req=2&csor=1&cb=jQuery1102060305102784707_1526436420940&=1526436420943
3) Code demonstration (note) – first attempt
If you write according to the above code, the result will be an error

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用vue-resource发送跨域请求</title>
    <!--引入vue、vue-resource文件-->
    <script src="vue.min.js"></script>
    <script src="vue-resource.min.js"></script>
</head>
<body>
    <div id="app">
        <button @click="sendJsonp">send</button>
    </div>
    <script>
            var vm = new Vue({
                el:"#app",
                methods:{
                    sendJsonp:function(){  
               this.$http.jsonp(&#39;https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su&#39;,{
                            params:{
                                wd:&#39;a&#39;
                            }
                        }).then(function(res){
                            console.log(res.data);
                        });
                    }
                }
            });
    </script>
</body>
</html>
Copy after login

The result will be an error

百度搜过How to use ajax in vuejs报错
Then why is this?

The parameter name of the 360 ​​search jsonp callback before was callback, while the parameter name used by Baidu was cb , so an error will be reported

The modified code is as follows

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用vue-resource发送跨域请求</title>
    <!--引入vue、vue-resource文件-->
    <script src="vue.min.js"></script>
    <script src="vue-resource.min.js"></script>
</head>
<body>
    <div id="app">
        <button @click="sendJsonp">send</button>
    </div>
    <script>
            var vm = new Vue({
                el:"#app",
                methods:{
                    sendJsonp:function(){
         this.$http.jsonp(&#39;https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su&#39;,{
                            params:{
                                wd:&#39;a&#39;
                            },
                            jsonp:&#39;cb&#39;
                        }).then(function(res){
                            console.log(res.data);
                        });
                    }
                }
            });
    </script>
</body>
</html>
Copy after login

4) Result

How to use ajax in vuejsHow to use ajax in vuejs

##4, Baidu search Case Demonstration

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>How to use ajax in vuejs列表</title>
    <style>
        .current{
            background-color:#CCCCCC;
        }
    </style>
    <!--引入vue、vue-resource文件-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.0"></script>
</head>
<body>
    <script>
    window.onload=function() {
        new Vue({
            el: "#app",
            data: {
                keyword: &#39;&#39;,
                myData:[],
                now: -1
            },
            methods: {
                getData(e) {
                    //如果按方向键上、下,则不发请求
                    if (e.keyCode == 38 || e.keyCode == 40)
                        return;
                    this.$http.jsonp(
                    &#39;https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su&#39;, {
                        params: {
                            wd: this.keyword
                        },
                        jsonp: &#39;cb&#39;
                    }).then(function (res) {
                        console.log(res.data.s);
                        this.myData = res.data.s;
                    });
                },
                changeDown() {
                    this.now++;
                    this.keyword = this.myData[this.now];
                    if (this.now == this.myData.length) {
                        this.now = -1;
                    }
                },
                changeUp() {
                    this.now--;
                    this.keyword = this.myData[this.now];
                    if (this.now == -2) {
                        this.now = this.myData.length - 1;
                    }
                }
            }
        });
    }
    </script>
    <div id="app">
        <input type="text" v-model="keyword"  
               @keyup="getData($event)" @keydown.down="changeDown"  
               @keydown.up.prevent="changeUp"
        />
        <ul>
            <li v-for="(val,index) in myData" :key="index"  
                               :class="{current:index==now}"
            >
                {{val}}
            </li>
        </ul>
    </div>
</body>
</html>
Copy after login

Related%20recommendations:%20">vue.js Tutorial"

The above is the detailed content of How to use ajax in vuejs. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template