• 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,除了写请求成功的回调函数外,还应该写上请求失败的回调函数。这样程序才健壮。

  • 相关阅读:
    087 类的继承
    086 一切皆对象
    085 对象的绑定方法
    在菜鸟教程学 HTML(一)
    生成输出 URL(16.2)
    创建分部视图(7.6.3)
    显示页面链接(7.5.1)
    NuGet 控制台代码
    浏览器对应用程序的根URL发出请求时所发生的情况(结合 DI)
    第 6 章 —— 依赖项注入(DI)容器 —— Ninject
  • 原文地址:https://www.cnblogs.com/imgss/p/6253411.html
Copyright © 2020-2023  润新知