vue-resource初體驗


這個插件是用於http請求的,類似於jquery的ajax函數,支持多種http方法和jsonp。

下面是resource支持的http方法。

get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'}, update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}

使用方法

標簽引入:

<script src="https://cdn.jsdelivr.net/vue.resource/1.0.3/vue-resource.min.js"></script>

模塊引入:

es6:

import Vue from 'vue';
import VueResource from 'vue-resource'
Vue.use(VueResource);

commonjs

var Vue = require('vue');
var VueResource = require('vue-resource');

Vue.use(VueResource);

 實例化一個resource對象

var resource = this.$resource('someItem{/id}');

 

一個例子:

{
  // GET方法請求的url,可以換成jsonp,
  this.$http.get('/someUrl').then(//在vue實例中使用,也可以全局使用Vue.resource
(response) => {
    // 如果請求成功,調用的回調函數,傳入響應的json數據作為參數
  },
 (response) => {
    // 出現錯誤時調用的回調函數
  });
}

 比如要從百度api請求一個天氣信息:

 getWeather() { //從百度api獲取天氣信息
                this.$http.jsonp(this.url)//用jsonp方法
                    .then((response) => { //異步
                        if (response) {
                            console.log(response);
                            this.weatherInfo = response.data.results[0]; } },(response)=>{console.log('error')});

完整代碼:

一個bug

在完成todolist(練手的小應用,詳情請戳<--)的天氣組件時原先的模板中,只有天氣組件的模板沒有v-if指令(與下面的代碼對比一下),這時運行時會出錯,原因見下面。

<template>
<ul class='weather'>
  <li><h3 style='display:inline; color: #f66'>{{weatherInfo.currentCity}}</h3>  |  pm2.5-{{weatherInfo.pm25}}</li>   
  <li>
    <ul>
      <li v-for="item in weatherInfo.weather_data" class='detail' @click='addClass'>
        <p title="詳情" class='date'>{{item.date.slice(0,10)}}</p>
        <p>
        <img :src="item.dayPictureUrl">
        <img :src="item.nightPictureUrl">
        </p>
        <p>{{item.weather}}</p>
        <p>{{item.wind}}</p>
        <p>{{item.temperature}}</p>
        </li>
    </ul>
  </li>
</ul>
</template>

 

原因就是服務器返回的數據晚vue渲染組件,雖然在created的鈎子函數調用了this.getweather()方法,但是在渲染組件時瀏覽器還沒有接收到返回數據,這時就會由於weatherInfo為null導致渲染失敗而報錯。解決辦法是加入v-if="weatherInfo",如果獲取了weatherInfo,則顯示組件,否則顯示加載的動畫。代碼如下:

<template>
    <!--顯示天氣界面-->
<ul class='weather' v-if="weatherInfo">//這里加入了v-if
  <li><h3 style='display:inline; color: #f66'>{{weatherInfo.currentCity}}</h3>  |  pm2.5-{{weatherInfo.pm25}}</li>   
  <li>
    <ul>
      <li v-for="item in weatherInfo.weather_data" class='detail' @click='addClass'>
        <p title="詳情" class='date'>{{item.date.slice(0,10)}}</p>
        <p>
        <img :src="item.dayPictureUrl">
        <img :src="item.nightPictureUrl">
        </p>
        <p>{{item.weather}}</p>
        <p>{{item.wind}}</p>
        <p>{{item.temperature}}</p>
        </li>
    </ul>
  </li>
</ul>
<!--加載動畫-->
    <p id="preloader_1" v-else>//沒有天氣數據就顯示加載動畫
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
    </p>
</template>

<script>
    export default {
        data() {
            return {
                url: 'http://api.map.baidu.com/telematics/v3/weather?location=上海&output=json&ak=HGOUnCXeQLEeywhGOu2jU29PFdC6duFF',
                weatherInfo: null,
                timer: null
            }
        },
        created() { //鈎子函數,組件創建完成時調用getWeather方法獲取天氣信息
            this.getWeather();

        },
        methods: {
            getWeather() { //從百度api獲取天氣信息
                this.$http.jsonp(this.url)
                    .then((response) => { //異步
                        if (response) {
                            console.log(response);
                            this.weatherInfo = response.data.results[0];
                        } else { //沒有響應就再發起一次
                            console.error('agian');
                            this.getWeather();
                        }
                    });
            },
            addClass(e) { //通過這個方法完成天氣信息的顯示和隱藏。
                if (e.currentTarget.nodeName == 'LI') {
                    var li = e.currentTarget;
                    if (!/show/.test(li.className)) {
                        li.className += ' show';
                    } else {
                        li.className = li.className.replace(' show', '');
                    }
                }

            }

        }
    }
</script>

 one more thing,除了寫請求成功的回調函數外,還應該寫上請求失敗的回調函數。這樣程序才健壯。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM