Vue 渐进式JavaScript 框架 基于Vue2的移动端项目:City组件
目录
City组件
创建城市组件
在src/views下创建CityView.vue文件。
示例如下:
路由设置
路由中增加city,在index.js中引入CityView.vue并设置路由配置。
示例如下:
import City from '@/views/CityView'
Vue.use(VueRouter) // 注册路由插件
// 配置表
const routes = [
{
path: '/films',
name: 'films',
component: Films,
children: [
{
path: '/films/nowplaying',
component: NowPlaying
},
{
path: '/films/comingsoon',
component: ComingSoon
},
{
path: '/films',
redirect: '/films/nowplaying'
}
]
},
......
{
path: '/cinemas',
name: 'cinemas',
component: Cinemas
},
{
path: '/city',
name: 'city',
component: City
},
设置跳转城市入口
在影院(cinemasView)中左侧城市绑定点击事件,
示例如下:
事件处理
点击后跳转到城市组件页面,如下:
methods: {
handleLeft () {
this.$router.push('/city')
}
},
城市列表
使用vant Indexbar,效果示例如下:
<template>
<div>
<van-index-bar>
<van-index-anchor index="A" />
<van-cell title="文本" />
<van-cell title="文本" />
<van-cell title="文本" />
<van-index-anchor index="B" />
<van-cell title="文本" />
<van-cell title="文本" />
<van-cell title="文本" />
</van-index-bar>
</div>
</template>
获取后端数据
通过请求后端接口获取城市列表,注意headers中的X-Host地址。
示例如下:
import http from '@/util/http'
export default {
mounted () {
http({
url: '/api/gateway?k=8627209',
headers: {
'X-Host': 'mall.film-ticket.city.list'
}
}).then(res => {
console.log(res.data.data.cities)
})
},
数据转换
需要把后端的数据转换为以下格式
赋值数据加数据转换
mounted () {
http({
// url: '/api/gateway?k=8627209',
url: 'http://localhost:8080/cityList.json',
headers: {
'X-Host': 'mall.film-ticket.city.list'
}
}).then(res => {
console.log(res.data.data.cities)
this.cityList = this.renderCity(res.data.data.cities)
})
},
methods: {
renderCity (list) {
const cityList = []
const letterList = []
for (let i = 65; i < 91; i++) {
letterList.push(String.fromCharCode(i))
}
letterList.forEach(letter => {
const newList = list.filter(item => item.pinyin.substring(0, 1).toUpperCase() === letter)
newList.length > 0 && cityList.push({
type: letter,
list: newList
})
})
return cityList
}
}
组件渲染
把城市列表改为使用后端数据渲染。
示例如下:
<template>
<div>
<van-index-bar>
<div v-for="data in cityList" :key="data.type">
<van-index-anchor :index="data.type" />
<van-cell :title="item.name" v-for="item in data.list"
:key="item.cityId" />
</div>
</van-index-bar>
</div>
</template>
自定义右侧导航
使用计算属性,示例如下:
设置计算属性
export default {
data () {
return {
cityList: []
}
},
computed: {
computedList () {
return this.cityList.map(item => item.type)
}
}
这样可以到达 右侧导航与左侧列表对应
热门城市
热门城市通过整体过滤参数中的ishot 显示在热门城市即可。
弹出字母
城市列表在下滑时的弹出相应字母功能,三方组件没有,需要自己实现。
可通过三方组件的select实现,change事件,首次进入就会触发。
下方事件通过默认参数获取参数后,直接弹出即可。
引入Toast
注意需要引入toast
import http from '@/util/http'
import { Toast } from 'vant'
在methods中定义事件处理中使用Toast轻提示
methods: {
handleChange (data) {
Toast(data)
},
修改弹出框样式
增加外部city类,防止设置样式影响其他
总结
Vue 渐进式JavaScript 框架 基于Vue2的移动端项目:City组件笔记