Vue 網(wǎng)絡(luò)請求數(shù)據(jù) vue-resource

一 創(chuàng)建測試項目

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

七 總結(jié)

1 了解js網(wǎng)絡(luò)庫vue-resource的使用,還有其他備選axios,fecth-jsonp
《1 安裝vue-resource
cnpm install vue-resource --save

《2 導(dǎo)入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數(shù)據(jù)方法。其他工具還有yapi swagger

八 參考

https://github.com/pagekit/vue-resource vue-resource代碼庫
https://jsonplaceholder.typicode.com/ 假的json數(shù)據(jù)api提供網(wǎng)站
https://fakejson.com/ 假的json數(shù)據(jù)生成網(wǎng)站

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容