Vue2.5 旅游项目实例14 城市选择页-动态数据渲染
创建分支:city-ajax
拉取到本地并切换分支:
git pull
git checkout city-ajax
然后在City.vue文件中发起axios请求:
import axios from 'axios' export default { data () { return { hotCity: [], cities: {} } }, created () { this.getCityList() }, methods: { getCityList () { axios.get('/api/city.json').then(this.getCityInfoSucc) }, getCityInfoSucc (res) { res = res.data console.log(res) if (res.ret && res.data) { this.hotCity = res.data.hotCities this.cities = res.data.cities } } } }
然后把根组件的数组传给子组件:
<city-list :hotCity="hotCity" :cities="cities"></city-list> <city-alphabet :cities="cities"></city-alphabet>
再到子组件List.vue中接收:
props: {
hotCity: Array,
cities: Object
},
开始定义热门城市和字母列表循环:
<div class="area"> <div class="title border-topbottom">热门城市</div> <div class="button-list"> <div class="button-wrapper" v-for="item in hotCity" :key="item.id"> <div class="button">{{item.name}}</div> </div> </div> </div> <div class="area" v-for="(item, key) in cities" :key="key"> <div class="title border-topbottom">{{key}}</div> <div class="item-list"> <div class="item border-bottom" v-for="v in item" :key="v.id">{{v.name}}</div> </div> </div>
因为cities是对象,所以循环要用键值key。
这时候刷新页面,已经可以看到数据渲染出来了。
然后需要渲染右侧的字母表列表,打开Alphabet.vue文件,编辑代码:
<template> <div class="list"> <ul> <li class="item" v-for="(item, key) in cities" :key="key">{{key}}</li> </ul> </div> </template> <script> export default { name: 'CityAlphabet', props: { cities: Object } } </script>
此时效果图:
提交代码并合并到master:
git add .
git commit -m "城市列表动态数据渲染"
git push
git checkout master
git merge city-ajax
git push