怎么用vue.js做异步请求


当前第2页 返回上一页

提交参数的两种形态:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

// 1.可以直接传入字符串 name=张三&age=19

// 2.可以以对象的形式传入{name:“三”,age:19}

<template>

 <div>

 </div>

</template>

<script>

export default {

  methods:{

   getData(){

   //axios-post请求传值

      this.$http({

          method:"post",

          url:"/getData2",

          headers:{

              'Content-type': 'application/x-www-form-urlencoded'

          },

          data:{

              name:'xxx'

          },

          transformRequest: [function (data) {//更改传值格式

              let ret = ''

              for (let it in data) {

                ret += encodeURIComponent(it) + '=' +

                encodeURIComponent(data[it]) + '&'

              }

              return ret.slice(0,ret.length-1)

            }],

      })

        .then(r => console.log(r))

        .catch(err => console.log(err))

    }

  }

  mounted(){//模板或el对应的html渲染完成后再调用里面的方法

 this.getData()

  }

}

</script>

<style scoped>

</style>

node后端:

1

2

3

4

5

6

7

8

server.post('/getData2',function(req,res){

  req.on("data",function(data){

      console.log(querystring.parse(decodeURIComponent(data)));

  });

  res.send({

    'msg':'bbb'

  })

})

二、vue-resource实现异步请求(和axios步骤基本相同)

1.项目中安装vue-resource

1

npm install --save vue-resource

2.在main.js中引入以供全局使用

1

2

import vueResource from 'vue-resource'

Vue.use(vueResource)//这儿有所不同

3.vue-resource之get请求

1

2

3

this.$http.get('/getData1')

    .then(r => console.log(r))//接口调用成功返回的数据

    .catch(err => console.log(err)),//接口调用失败返回的数据

4.vue-resource之post请求

1

2

3

this.$http.post('/getData2',{name:"bbb"})

    .then(r => console.log(r))//接口调用成功返回的数据

    .catch(err => console.log(err)),//接口调用失败返回的数据

以上就是怎么用vue.js做异步请求的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

vue项目中关闭eslint校验的方法介绍

vue中computed和watch的区别是什么?

vue cli是什么

vue中路由之间如何通讯?方法介绍

vue如何动态增加css

javascript之ssm+vue前后端分离框架整合实现

vue哪一年出来的

vue和react中dom的区别

vue全家桶有哪些

vue.js用什么编辑器

更多相关阅读请进入《vue》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...