Vue-resource 实现 get, post请求

Vue-resource是Vue高度集成的第三方包,能很方便的发送请求。

注意Vue-resource依赖于Vue,只能在Vue环境下使用。

在html中使用vue-resource

  • 导包
//依赖于Vue
<script src="./js/vue.js"></script>
<script src="./js/elementui.js"></script>
//导包
<script src="./js/vue-resource.min.js"></script>
  • 使用:

请求方法(请求url,请求体body,可选参数options)

get(url,[options])

head(url,[options])

delete(ur1,[options])

jsonp(url,[options])

//body是要发送给服务器的数据对象  以对象的形式存在
post(url,[body],[options])

put(url,[body],[options])

patch(url,[body],[options])
全局使用:
// global Vue object
Vue.http.get('/someUrl',[options]).then(successCallback, errorCallback);
Vue.http.post('/someUr1',[body],[options]).then(successCallback, errorCallback);
Vue实例中使用:
this.$http.get('/someUr',[options]).then(successCallback,errorCallback);
this.$http.post('/someUr',[body],[options]).then(successCallback,errorCallback);
 例子:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/commen.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="css/elementui.css">
    <title>Document</title>
</head>

<body>
<div id="app">
    <input type="button" value="get请求" @click="getMessage">
    <input type="button" value="post请求" @click="postMessage">
</div>
</body>
</html>

<!-- 引入组件库 -->
<script src="./js/vue.js"></script>
<script src="./js/elementui.js"></script>
<script src="./js/vue-resource.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data: function(){
        return{}
        },
        methods: {
            getMessage(){
                this.$http.get('http://localhost:3003/compilerOptions').then(function(result){
                    console.log(result)
                })
            },
            postMessage(){
                this.$http.post('http://localhost:3003/compilerOptions',{}).then(function(result){
                    console.log(result.body)
                })
            }
        }
    });

</script>
<style>

</style>
get请求: 

post请求: 

在vue项目中使用vue-resource:

  •  安装vue-resource:
 cnpm install vue-resource --save-dev
  • 在main.js中引入:
import VueResource from 'vue-resource'
Vue.use(VueResource)

完成,之后可以在项目中使用了:

<template>
  <div>
    <Head1/>
    <Body1/>
    <Footer1/>
  </div>
</template>

<script>

export default {
  name: "pageOne",
  created() {
    this.getMessage()
  },
  methods: {
    getMessage() {
      this.$http.get('http://localhost:3000/data').then(function (result) {
        console.log(result.body)
      })
    },
  }
}
</script>

<style scoped>

</style>

成功请求到数据:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值