编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Vue进阶(二十):Vue中的请求方式(vueajax请求的五个步骤)

wxchong 2024-08-04 02:44:14 开源技术 24 ℃ 0 评论

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等参数。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表