vue-resource的安裝及使用,請求http數據。

1.安裝vue-resource。

首先在命令行中找到項目位置【非常重要】,然後輸入:

npm install --save vue-resource 

這裏寫圖片描述

安裝成功後,打開項目的package.json可以查看到vue-resource的版本信息。
這裏寫圖片描述

2.導入vue-resource

在組件中使用之前,一定要先導入vue-resource。導入方法爲:
打開main.js,輸入:

import Resource from 'vue-resource'

Vue.use(Resource)

如圖
這裏寫圖片描述

3.使用get請求獲取數據。

在需要獲取數據的組件中,創建get請求來獲取數據。這裏我們的項目中是在App.vue父組件中使用。
爲了保證頁面數據顯示正確,我們在App.vue組件中創建created生命週期鉤子函數,在生成DOM之前加載好數據。
APP.vue中,需要在data中創建一個seller對象接收傳遞過來的數據。因爲data.json裏的seller數據是一個對象,後面的goods和ratings是數組。

<template>
  <div>
    <v-header :seller="seller"></v-header>//在使用的組件中傳入seller的數據。
  </div>...
</template>

<script>
import header from './components/header/header.vue'
const ERR_OK = 0
export default {

  data () {
    return {
      seller: {}
    }
  },

  created () {
    this.$http.get('/api/seller').then((response) => {
      response = response.body
      console.log(response)
      if (response.errno === ERR_OK) {
        this.seller = response.data
        console.log(this.seller)
      }
    })
  },
 }
</script>

4.在子組件中使用數據。

在子組件中(header)的props中接收seller,就可以在頁面中使用seller

  props: {
    seller: {
      type: Object
    }
  },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章