1. 程式人生 > >自學vue 之使用axios獲取ajax資料請求和首頁父子元件資料傳遞部分筆記

自學vue 之使用axios獲取ajax資料請求和首頁父子元件資料傳遞部分筆記

使用axios獲取ajax資料請求:

      首先還是線上建立分支 git pull 拉到本地,並 git checkout index-ajax 切換到該分支,執行命令 npm install axios -- save 安裝 axios 依賴包 ,在首頁home.vue元件中引入 axios ,引入程式碼如下:

注意事項:

(1)axios.get 資料的index.json路徑需要放置於static(靜態檔案放置資料夾)/mock檔案下才能訪問,而模擬資料一般不提交到線上,所以需要在.gitignore 中加入static/mock, 則該檔案內容不會被提交到線上或本地

(2) 同樣,直接訪問路徑'/static/mock/index.json'是不可取的的,需要在上圖左邊第二個檔案config下的index.js中proxyTable設定代理路徑,如下圖所示;則代理路徑'/api/index.json'就相當於'static/mock/index.json',就可以進行訪問啦~


 

首頁父子元件資料傳遞:

    在首頁父元件home.vue程式碼如下:

<template>
    <div>
      <!--data資料中的返回值通過屬性的形式傳給子元件-->
      <home-header :city="city"></home-header>
      <home-swiper :list="swiperList"></home-swiper>
      <home-icons :list="iconList"></home-icons>
      <home-recommend :list="recommendList"></home-recommend>
      <home-weekend :list="weekendList"></home-weekend>
    </div>
</template>

<script>
import HomeHeader from './components/Header'
import HomeSwiper from './components/Swiper'
import HomeIcons from './components/Icons'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import axios from 'axios'   //引入 axios
export default {
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  data () {          //父元件新增data資料
    return {
      city: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },
  methods: {                  //使用axios 傳送ajax資料請求
    getHomeInfo () {
      axios.get('/api/index.json')
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      res = res.data
      if (res.ret && res.data) {    //判斷ajax請求資料,並進行相應資料渲染(賦值)
        const data = res.data
        this.city = data.city
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  mounted () {
    this.getHomeInfo()
  }
}
</script>

     子元件接收資料程式碼如下:

注意事項:

(1)子元件通過 props 接收父元件傳輸的資料內容 再將對應子元件的資料進行取值修改

(2)在swiper子元件中,為防止輪播圖預設不是第一個圖片顯示,加入computed計算屬性showSwiper並加在相應位

(3)為解決輪播圖不自動滾動: 將autoplay屬性: false ;loop: true 的效果是無縫輪播

最後,在home.vue元件中將獲取的ajax資料取出,渲染即可~