微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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',[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  href="css/index.css">
    <link  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>

成功请求到数据:

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐