數(shù)據(jù)請(qǐng)求步驟:
一跟衅、vue-resource的配置:
1、在相應(yīng)的工程中(注意:一定要在相應(yīng)的項(xiàng)目文件夾中) npm install vue-resource --save(‘save’的作用是將模塊保存在package.json中播歼,以便項(xiàng)目轉(zhuǎn)接時(shí)省事);
2伶跷、在main.js中 import VueResource from 'vue-resource'(從'Vue-resource'中引入模塊,并命名為'VueResource');
3秘狞、Vue.use(VueResource);(官方插件都這樣用)
二叭莫、使用:
1、在組件中使用:(以QQ音樂(lè)接口為例)
let api='https://api.bzqll.com/music/tencent/songList?key=579621905&id=1147906982';//QQ音樂(lè)接口
this.$http.get(api).then(function(reponse){
console.log(reponse)
},function(err){
console.log(err)
})
代碼:
main.js:
// The Vue build version to load with the import
command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'Vue-resource'
//從'Vue-resource'中引入模塊烁试,并命名為'VueResource'
Vue.config.productionTip = false;
Vue.use(VueResource);//官方插件都這樣用
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Home.vue:
<template>
<div>
<h2>這是一個(gè)首頁(yè)組件</h2>
<button @click="getData()">請(qǐng)求數(shù)據(jù)</button>
<ul>
<li v-for="item in list">{{item}}</li>
</ul>
</div>
</template>
<script>
// npm install vue-resource --save:save的意思是將vue-resource寫(xiě)入package.json
export default {
name: "home",
data(){
return {
msg:'我是一個(gè)首頁(yè)',
list:[],
}
},
methods:{
getData(){
let api='https://api.bzqll.com/music/tencent/songList?key=579621905&id=1147906982';//QQ音樂(lè)接口
this.$http.get(api).then(function(response){
console.log(response.body.data.songs);
this.list=response.body.data.songs;
},function(err){
console.log(err)
})
}
},
}
</script>
<style scoped lang="scss">
h2{
color:red;
}
</style>