美文网首页
11、Vue之vue-resource 请求数据(官方自带模块)

11、Vue之vue-resource 请求数据(官方自带模块)

作者: msqt | 来源:发表于2019-03-06 21:03 被阅读0次

    数据请求步骤:
    一、vue-resource的配置:
    1、在相应的工程中(注意:一定要在相应的项目文件夹中) npm install vue-resource --save(‘save’的作用是将模块保存在package.json中,以便项目转接时省事);


    image.png

    2、在main.js中 import VueResource from 'vue-resource'(从'Vue-resource'中引入模块,并命名为'VueResource');
    3、Vue.use(VueResource);(官方插件都这样用)


    image.png

    二、使用:
    1、在组件中使用:(以QQ音乐接口为例)
    let api='https://api.bzqll.com/music/tencent/songList?key=579621905&id=1147906982';//QQ音乐接口
    this.$http.get(api).then(function(reponse){
    console.log(reponse)
    },function(err){
    console.log(err)
    })

    image.png

    代码:


    image.png

    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>这是一个首页组件</h2>
    <button @click="getData()">请求数据</button>
    <ul>
    <li v-for="item in list">{{item}}</li>
    </ul>
    </div>
    </template>


    <script>
    // npm install vue-resource --save:save的意思是将vue-resource写入package.json
    export default {
    name: "home",
    data(){
    return {
    msg:'我是一个首页',
    list:[],
    }
    },
    methods:{
    getData(){
    let api='https://api.bzqll.com/music/tencent/songList?key=579621905&id=1147906982';//QQ音乐接口
    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>

    相关文章

      网友评论

          本文标题:11、Vue之vue-resource 请求数据(官方自带模块)

          本文链接:https://www.haomeiwen.com/subject/lxcfpqtx.html