前面我们已经将首页部分的开发分为了几个模块,下面我们开始进行编码。
首先看一下我的首页项目组成,我们通过五个vue模块组件最后实现一个Home.vue首页的实现。
一、首先来看一下Home.vue这一总的部分的代码:
<template>
<div>
<!-- 父组件通过属性的形式给子组件传值 ,子组件需要接收父组件传过来的值-->
<!-- 这个地方的city是data中的city,data中的city是methods中通过ajax获得的 -->
<home-header :city="city"></home-header>
<home-swipe :list="swiperList"></home-swipe>
<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 HomeSwipe from './components/Swipe'
import HomeIcons from './components/Icons'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import axios from 'axios'
export default {
name: 'Home',
//引入了子组件Header,需要声明局部组件
components:{
HomeHeader:HomeHeader,
HomeSwipe:HomeSwipe,
HomeIcons:HomeIcons,
HomeRecommend:HomeRecommend,
HomeWeekend:HomeWeekend
},
data: function() {
return{
// data中的city、swiperList等数据都是通过methods中ajax获得的
city: '',
swiperList: [],
iconList: [],
recommendList: [],
weekendList: []
}
},
mounted (){
//页面挂载好了之后去执行getHomeInfo函数
this.getHomeInfo()
},
methods: {
getHomeInfo: function(){
//使用axios.get去请求一个url
axios.get('/api/index.json')
//获取信息成功的返回函数
.then(this.getHomeInfoSucc)
},
//获取信息成功的返回函数
getHomeInfoSucc: function (res) {
res=res.data
if (res.ret && res.data) {
this.city=res.data.city
this.swiperList=res.data.swiperList
this.iconList=res.data.iconList
this.recommendList=res.data.recommendList
this.weekendList=res.data.weekendList
}
}
}
}
</script>
<style>
</style>
我们来逐步分析一下这块代码,我们知道Vue文件主要由三部分组成,分别是:模板template部分、逻辑script部分和样式style部分。
首先我们引入了下面五个子组件和一个与服务端进行通讯的插件axios:
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。要使用它就必须先在我们的项目中安装它,安装非常简单,只需在控制台输入下面一句代码就可以了:
npm install axios
然后在我们引入了上面五个子组件之后,就需要在我们的组件中声明这五个局部组件
然后我们定义需要向子组件传递的data,代码如下:
然后city、swiperList等data的值我们是从哪儿获得的呢?首先我们使用一个页面挂载钩子函数,等页面挂载完成之后,我们使用axios去请求数据,这里我们在本地模拟了服务器端的数据,新建了一个index.json的文件
index.json里面模拟的数据我也放到这儿:
{
"ret": true,
"data": {
"city": "北京",
"swiperList": [{
"id": "0001",
"imgUrl": "http://img1.qunarzz.com/piao/fusion/1801/1a/94428c6dea109402.jpg_640x200_2cf590d8.jpg"
},{
"id": "0002",
"imgUrl": "http://img1.qunarzz.com/piao/fusion/1802/42/7c92b9a381e46402.jpg_640x200_1cdce2a4.jpg"
},{
"id": "0003",
"imgUrl": "http://img1.qunarzz.com/piao/fusion/1802/51/e78f936a5b404102.jpg_640x200_c14f0b3a.jpg"
},{
"id": "0004",
"imgUrl": "http://img1.qunarzz.com/piao/fusion/1712/91/a275569091681d02.jpg_640x200_0519ccb9.jpg"
}],
"iconList": [{
"id": "0001",
"imgUrl": "http://img1.qunarzz.com/piao/fusion/161