Vue.js学习系列(十)---给页面增加动态数据

    xiaoxiao2021-03-25  97

    前面的文章写的页面都是静态的,也就是说数据是固定不变的。在实际的应用中,需要请求外部数据以动态改变页面内容。对应有一个库叫 vue-resource 帮我们解决这个问题。

    使用命令行安装

    cnpm install vue-resource –save

    main.js引入并注册 vue-resource

    import VueResource from 'vue-resource'

    Vue.use(VueResource);

    我们在 secondcomponent.vue 上来动态加载数据

    添加一个列表:

    <ul>

          <li v-for="article in articles">

            {{article.title}}

          </li>

    </ul>

     data 里面加入数组 articles 并赋值为[]

    然后在 data 后面加入加入钩子函数 mounted(详细请参照官方文档关于 vue 生命周期的解析)data 和 mount中间记得记得加逗号

    mounted: function() {

        this.$http.jsonp('https://api.douban.com/v2/movie/top250?count=10', {}, {

            headers: {

     

            },

            emulateJSON: true

        }).then(function(response) {

          // 这里是处理正确的回调

     

            this.articles = response.data.subjects

            // this.articles = response.data["subjects"] 也可以

     

        }, function(response) {

            // 这里是处理错误的回调

            console.log(response)

        });

      }

    这里使用的是豆瓣的公开 GET 接口,如果接口是跨域的 POST 请求,则需要在服务器端配置:

    Access-Control-Allow-Origin: *

    这时候运行看看。等一会接口返回数据,咦,数据加载出来了,棒棒哒 !

     

     

    转载请注明原文地址: https://ju.6miu.com/read-14896.html

    最新回复(0)