自定义 ajax 请求
自定义 ajax 请求
使用 vue-resource 请求
使用 axios 请求
--------------------------------------------------------
这里介绍几种:vue网络请求的方法:
1。自定义 ajax 请求
先写一个组件:
<template>
<div class="hello">
<button class="mybtn" type="button" name="button" @click="getData">点击请求</button>
<ul>
<li v-for="(data,index) in datas">
<span>
{{data.name}}
</span>
<span style="margin-left:10px;">
{{data.address}}
</span>
</li>
</ul>
</div>
</template>
<script>
// 局部使用
// import ajax from '../js/customAjax'
export default {
name: 'HelloWorld',
data () {
return {
datas:[]
}
},
methods:{
getData() {
var that = this
// 全局注册可以添加一个 this
this.ajax({
methods:'GET',
url:'../static/mydata.json',
data:{},
success:function(res){
console.log(res)
console.log('请求成功,成功的状态码是:'+res.status)
if(res.status=='0001'){
that.datas = res.datas
}
},
faile:function(res) {
console.log(res)
}
})
}
}
增加vue 封装的ajax 请求:
let params = []
// 遍历请求参数对象,拼接请求参数
for(let param in options.data){
params.push(param +'='+options.data[param])
}
// 给每个数组后面添加一个 &
let requestData = params.join('&')
// 请求类型
let requestType = options.methods.toUpperCase()
// 如果是 GET 请求
if(requestType == 'GET'){
xhr.open(requestType,options.url+'?'+requestData,options.async)
xhr.send()
}else if(requestType == 'POST'){ // 如果是 POST 请求
xhr.open(requestType,options.url,options.async)
xhr.setRequestHeader("Content-type",
"application/x-www-form-urlencoded;charset=utf-8");
xhr.send(requestData)
}
xhr.onreadystatechange = function() {
if (xhr.readyState==4 && xhr.status==200) {
options.success(JSON.parse(xhr.responseText))
}else if(xhr.status!=200) {
options.faile('request error')
}
}
}
3.App导入即可:
2.JqueryAjax请求:
基本一致:
<script>
export default {
name: 'HelloWorld',
data () {
return {
datas:[]
}
},
methods:{
getdata() {
var that = this
$.ajax({
type:'GET',
url:'../static/mydata.json',
dataType:"json",
success:function(res){
if(res.status =='0001'){
that.datas = res.datas
}
console.log(res)
},
error:function(error) {
console.log('error')
}
})
}
}
}
</script>
3.使用 vue-resource 请求:
methods:{
// 本地请求 json 模拟
getData() {
var that = this
this.$http.get('../static/mydata.json').then(response =>{
console.log(response)
if(response.body.status == '0001'){
that.datas = response.body.datas
that.isShowNativeResult = true
that.isShowGankIoResult = false
}
},response => {
console.log('error')
that.isShowNativeResult = false
that.isShowGankIoResult = false
})
},
4.使用 axios 请求
xios 简介
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
- demo:
-
methods:{ // 本地请求 json 模拟 getData() { var that = this this.$axios.get('../static/mydata.json') .then(response =>{ console.log(response.data) if(response.data.status == '0001'){ that.datas = response.data.datas that.isShowNativeResult = true that.isShowGankIoResult = false } }) .catch(error =>{ console.log(error) that.isShowNativeResult = false that.isShowGankIoResult = false }) },