例子:Vue 配合 vue-resource 從接口獲取數據

vue-resource 是 vue 的一個與服務器端通訊的 HTTP 插件,用來從服務器端請求數據。html

結合例子——圖片列表來寫一下 Vue獲取接口數據。vue

html :數組

<div id="app">
    <ul>
        <li>
            <img v-for="imgItem in imgList" v-bind:src="imgItem.img" alt="" width="100%" height="100%"/>
        </li>
    </ul>
</div>

vue :promise

var vm = new Vue({ el:'#app', data: { imgList:[], getImgUrl: ''    //這裏寫接口地址
 }, created: function(){ this.getImg()              //定義方法
 }, methods: { getImg: function(){ var that = this; that.$http({ //調用接口
                    method:'GET', url:this.getImgUrl   //this指data
                }).then(function(response){  //接口返回的數據
                    this.imgList=response.data; // promise的then成功以後,將response返回的數據data,保存到imgList數組裏
                },function(error){ console.log(error); }) } } })
相關文章
相關標籤/搜索