美文网首页前端技术
Vue 网络请求数据 vue-resource

Vue 网络请求数据 vue-resource

作者: 剑有偏锋 | 来源:发表于2018-07-30 16:37 被阅读176次

一 创建测试项目

vue init webpack-simple vuedemo

二 进入demo目录

cd vuedemo

三 安装依赖

cnpm install

四 安装vue-resource

//从包管理下载vue-resource包,并更新到项目的package.json里
cnpm install vue-resource --save

五 修改代码

├── src
│ ├── App.vue
│ ├── components
│ │ └── Home.vue
│ ├── main.js

App.vue

<template>
  <div id="app">
<v-home></v-home>
<hr>
  </div>
</template>

<script>
/*
import components
Local Registration components
use in template
*/

import Home from './components/Home.vue';

export default {
  name: "app",
  data() {
    return {
      msg:'hello vue world!',     
    };
  },
  components:{
    'v-home':Home
  }
};
</script>

<style>

</style>

Home.vue

<template>
    <!-- all content need in root-->
    <div id="home">
        <h2>{{msg}}</h2>


        <button @click="getData()">request data</button>
        <hr>
        <br>

        <ul>
            <li v-for='item in list' :key="item.id">
                {{item.website}}
            </li>
        </ul>
    </div>
</template>


<script>

export default {
    data(){
        return {
            msg:'i am home component!',
            list:[]
        }
    },
    methods: {
        getData(){
            var api='https://jsonplaceholder.typicode.com/users'

            this.$http.get(api).then((response)=>{
                console.log(response)

                this.list=response.body;

            }, function(err){
                console.log(err)
            })
        }
    },
    mounted(){
        this.getData()
    }

}
</script>

<style>

#home h2{
    color: red;
}
</style>

main.js

import Vue from 'vue'
import App from './App.vue'

import VueResource from 'vue-resource'
Vue.use(VueResource)

new Vue({
  el: '#app',
  render: h => h(App)
})

六 运行

npm run dev


image.png

七 总结

1 了解js网络库vue-resource的使用,还有其他备选axios,fecth-jsonp
《1 安装vue-resource
cnpm install vue-resource --save

《2 导入vue-resource
main.js
import VueResource from 'vue-resource'
Vue.use(VueResource)

《3 使用vue-resource
thos.$http.get(url).then((response)=>{

},function(err){

})

2 批量假的json的api,及批量生成假json数据方法。其他工具还有yapi swagger

八 参考

https://github.com/pagekit/vue-resource vue-resource代码库
https://jsonplaceholder.typicode.com/ 假的json数据api提供网站
https://fakejson.com/ 假的json数据生成网站

相关文章

网友评论

    本文标题:Vue 网络请求数据 vue-resource

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