1. 程式人生 > >vue專案及axios請求獲取資料

vue專案及axios請求獲取資料

一般vue專案中 一個頁面是由多個元件組成的,各個組建的資料都是統一在主介面的元件中傳送axios請求獲取,這樣極大地提高了效能。

  • 首先要匯入用到的元件和axios
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' export default { name: 'Home', components: { HomeHeader, HomeSwiper, HomeIcons, HomeRecommend, HomeWeekend },
  • 在data中將要用到的資料給一個初始值,為空
  data () {
    return {
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList
: [] }
},
  • 在methods中寫方法,傳送axios獲取資料
methods: {
    getHomeInfo () {
      axios.get('/api/index.json')
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      res=res.data
      if (res.ret && res.data) {
        const data = res.data
        this.swiperList = data.swiperList
        this
.iconList = data.iconList this.recommendList = data.recommendList this.weekendList = data.weekendList } } }, mounted () { this.getHomeInfo() } }
  • 傳遞資料
<div>
  <home-header></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>