Vue-Resource基礎介紹

vue-resource的請求API是按照REST風格設計的,它提供了7種請求API:

  • get(url, [options])
  • head(url, [options])
  • delete(url, [options])
  • jsonp(url, [options])
  • post(url, [body], [options])
  • put(url, [body], [options])
  • patch(url, [body], [options])

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue-resource</title>
   <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="../../node_modules/"></script>
  <script src="../../node_modules/vue-resource/dist/vue-resource.js"></script>
</head>
<body>
<div id="app" class="container">
  <h2>vue-resource插件講解</h2>
  <a href="javascript:;" class="btn btn-primary" @click="get">發送Get請求</a>
  <a href="javascript:;" class="btn btn-primary" @click="post">發送Post請求</a>
  <a href="javascript:;" class="btn btn-primary" @click="jsonp">發送Jsonp請求</a>
  <a href="javascript:;" class="btn btn-primary" @click="http">發送htttp請求</a>
</div>
<script type="text/javascript">
  new Vue({
    el: "#app",
    data: {

    },
    mounted: function () {
      // 全局攔截器
      Vue.http.interceptors.push(function (request, next) {
        console.log("request init");
        next(function (response) {
          console.log("response init.");
          return response;
        });
      });
    },
    http:{
      // 對全局路徑的配置
      root: "api/"
    },
    methods: {
      get: function () {
        this.$http.get("http://www.imooc.com/course/AjaxCourseMembers?ids=796",{
          params: {
            userId: "101"
          },
          headers: {
            token: "abcd"
          }
        }).then(res=>{
          this.msg = res.data;
        },error=>{
          this.msg = error;
        })
      },
      post: function () {
        this.$http.post("package.json",{
          userId: "102"
        },{
          headers:{
            access_token: "abc"
          }
        }).then(function (res) {
            this.msg = res.data;
        });
      },
      jsonp: function () {
        this.$http.jsonp("http://www.imooc.com/course/AjaxCourseMembers?ids=796").then(function (res) {
            this.msg = res.data;
        })
      },
      // 以配置的方式調用
      http: function () {
        this.$http({
          url: "package.json",
          params: {
            userId: "103"
          },
          headers: {
            token: "123"
          },
          timeout: 5,
          before: function () {
            console.log("before init")
          }
        }).then(function (res) {
          this.msg = res.data;
        });
      }
    }
  });
</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章