目标: 城市页面的动态数据渲染
1. 准备阶段:
创建分支,构建组件模板,引入组件。
与首页一样,将我们的city.json数据放在静态资源文件夹内,并让City.vue组件来获取ajax数据。
2. 获取ajax数据
- 引入 axios
- 借助生命周期函数的mounted, 让页面挂载好之后去执行getCityInfo这个函数(函数定义在methods中)
export default {
name: 'City',
components: {
CityHeader,
CitySearch,
CityList,
CityAlphabet
},
methods: {
getCityInfo () {
axios.get('api/city.json')
.then(this.handleGetCityInfoSucc)
},
handleGetCityInfoSucc (res) {
console.log(res) //返回一个ret和一个data对象
}
},
mounted () {
this.getCityInfo()
}
}
- 在首页获取ajax数据进行页面渲染的时候,已经将用户对/api的请求转移到mock目录下,因此这里可以直接访问city.json数据。
3. 父子组件数据传递
流程与首页的相同,具体参考06-home-ajax.md文档。
注意:在字母与对应城市的数据渲染部分会涉及到一个双层的循环,因为我得到的这部分数据是一个数组对象,该对象的key是字母,value是每个项的数据,它是数组类型的。
<div class="area"
v-for="(item, key) of cities"
:key="key"
>
<div class="title border-topbottom">{{key}}</div>
<div class="item-list">
<div
class="item border-bottom"
v-for="innerItem of item"
:key="innerItem.id"
>{{innerItem.name}}</div>
</div>
</div>
呈现右侧字母表的部分:
<ul>
<li class="item" v-for="(item,key) of cities" :key="key">{{key}}</li>
</ul>