龙空技术网

Vue进阶(二十):Vue中的请求方式

Web全栈开发攻城狮 229

前言:

当前咱们对“vue中请求数据”大约比较关怀,你们都需要分析一些“vue中请求数据”的相关知识。那么小编在网上搜集了一些关于“vue中请求数据””的相关资讯,希望大家能喜欢,同学们快快来学习一下吧!

resource请求

cnpm install vue-resource --save import VueResource from 'vue-resource'Vue.use(VueResource)this.$http.get("")
axios 请求方式一
cnpm install axios --save axios.defaults.baseURL = "根地址"//vue页面引入import axios from 'axios'axios.get(请求的地址)
axios 请求方式二
cnpm install axios --save Vue.prototype.http = axios //配置Vue原型this.http.get("")
fetch(“”) // es6的请求方式

fetch是新一代XMLHttpRequest的一种替代方案。无需安装其他库。可以在浏览器中直接提供其api轻松与后台进行数据交互。

基本用法:

fetch(url,{parmas}).then(res=>      return res.json()  //返回promise对象 ).then(data=>{  return data     //返回真正数据}).catch(err=>{ throw new Error(err)})

(1) get 方式:

注意:如果是提交表单元素,那么一定要添加headers参数, 而且content-Type的值必须是application/x-www-form-urlencoded

heders:{	‘Content-Type’:“application/x-www-form-urlencoded”},

(2)通过vuex请求数据

export default {  name:"Login2",  data(){    return{      mobile:"",        password:"",      val:""    }  },  methods:{      go(){       var data={            mobile:this.mobile,            password:this.password       }       this.$store.dispatch("login",data).then(res=>{           this.arr=res.data.data       }).catch(err=>{           console.log("登录;err",err)       })      }  }}

store.js 中对应的action

 login({commit},payload){        return new Promise((resolve,reject)=>{           fetch("/account/login",payload).then(res=>{                   resolve(res)           }).catch(err=>{                   console.log("登录--err:",err)                  reject(err)           })        })     },

通过vuex实现请求,fetch发送请求可以不用带methodbodyheaders等参数。

标签: #vue中请求数据