Home > Article > Web Front-end > How to use ajax in vuejs
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.
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:'get', url:'user.json' }).then(function(res){ console.log(res.data.name); }); } } }); </script> </body> </html>
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();
(2) Use transformRequest to convert the request before sending it Data conversion
axios.post('url',data,{ transformRequest:[ function(data){ let params = ''; for(let index in data){ params +=index+'='+data[index]+'&'; } return params; } ] }).then(function(res){ console.log(res.data) });
(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
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
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('https://sug.so.360.cn/suggest',{ params:{ word:'a' } }).then(function(res){ console.log(res.data); }); } } }); </script> </body> </html>
4) Results
3. Basic example demonstration (Baidu search)
1) The requirements are the same as those of 360 search
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('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{ params:{ wd:'a' } }).then(function(res){ console.log(res.data); }); } } }); </script> </body> </html>
The result will be an error
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('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{ params:{ wd:'a' }, jsonp:'cb' }).then(function(res){ console.log(res.data); }); } } }); </script> </body> </html>
4) Result
##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: '', myData:[], now: -1 }, methods: { getData(e) { //如果按方向键上、下,则不发请求 if (e.keyCode == 38 || e.keyCode == 40) return; this.$http.jsonp( 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su', { params: { wd: this.keyword }, jsonp: 'cb' }).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>Related recommendations: "
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!