vue手写城市组件

606 阅读1分钟

1. 预览城市组件

城市组件预览.gif

2. 组件基础结构代码

<template>
  <div class="xtx-city" ref="target">
    <div class="select">
      <span class="placeholder">北京市市辖区</span>
      <span class="value"></span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-show="visible">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span
          class="ellipsis"
          v-for="item in 30"
          :key="item"
          >北京市</span
        >
      </template>
    </div>
  </div>
</template>

<script>
export default {
  name: 'City',
  props: {
    fullLocation: {
      type: String,
      default: ''
    }
  }  
}
</script>
<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
.loading {
  height: 290px;
  width: 100%;
  background: url("~@/assets/images/loading.gif") no-repeat center;
}
</style>

3. 实现功能代码:

<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggle" :class="{ active: visible }">
      <span class="placeholder">{{ fullLocation }}</span>
      <span class="value"></span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-show="visible">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span
          class="ellipsis"
          v-for="item in curList"
          :key="item.code"
          @click="changeItem(item)"
          >{{ item.name }}</span
        >
      </template>
    </div>
  </div>
</template>

<script>
import { onClickOutside } from '@vueuse/core'
import { ref, reactive, computed } from 'vue'
import axios from 'axios'
const getCityData = () => {
  const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
  return axios({ url })
}
export default {
  name: 'City',
  props: {
    fullLocation: {
      type: String,
      default: ''
    }
  },
  setup (props, { emit }) {
    const visible = ref(false)
    const cityData = ref([])
    const loading = ref(false)
    // 显示城市组件
    const open = () => {
      visible.value = true
      // 检查在window中是否有数据
      if (window.cityData) {
        // 有数据就从window拿取
        cityData.value = window.cityData
      } else {
        // 没有数据就获取数据
        // 获取城市数据、
        // 加载中
        loading.value = true
        getCityData().then(res => {
          cityData.value = res.data
          // 把数据存到window中
          window.cityData = res.data
          // 加载完成
          loading.value = false
        })
      }
    }

    // 隐藏城市组件
    const close = () => {
      visible.value = false
      // 清空选择的痕迹
      for (const key in selectResult) {
        selectResult[key] = ''
      }
    }

    // 切换显示和隐藏
    const toggle = () => {
      visible.value ? close() : open()
    }

    // 点击其他位置隐藏
    const target = ref(null)
    onClickOutside(target, () => {
      close()
    })

    // 定义保存用户点击的数据
    const selectResult = reactive({
      provinceCode: '', // 省
      provinceName: '', // 省的名字
      cityCode: '', // 市
      cityName: '', // 市的名字
      countyCode: '', // 区
      countyName: '', // 区的名字
      fullLocation: '' // 组合
    })

    const curList = computed(() => {
      // 省份
      let currList = cityData.value
      // 城市
      if (selectResult.provinceCode) {
        currList = currList.find(p => p.code === selectResult.provinceCode).areaList
      }
      // 地区
      if (selectResult.cityCode) {
        currList = currList.find(c => c.code === selectResult.cityCode).areaList
      }
      return currList
    })

    // 当前点击的城市
    const changeItem = (item) => {
      if (item.level === 0) {
        // 点击的是省(保存用户每次点击的选择)
        selectResult.provinceCode = item.code
        selectResult.provinceName = item.name
      }
      if (item.level === 1) {
        // 点击的是市(保存用户每次点击的选择)
        selectResult.cityCode = item.code
        selectResult.cityName = item.name
      }
      if (item.level === 2) {
        // 点击的是区(保存用户每次点击的选择)
        selectResult.countyCode = item.code
        selectResult.countyName = item.name
        selectResult.fullLocation = selectResult.provinceName + selectResult.cityName + selectResult.countyName
        // 通知父组件当前用户的选择
        emit('adress-change', selectResult)
        // 关闭弹层,通知父组件当前用户的选择
        close()
      }
    }
    return { visible, toggle, target, changeItem, curList, loading }
  }
}
</script>

4 注意点

4.1 需要传递的值

props: {
    fullLocation: {
      type: String,
      default: ''
    }
  },

从父组件传进来的值,是为了要默认显示在页面中

4.2 在组件外部点击隐藏

这里需要实现城市组件弹框出来再其他位置点击都要收起弹窗的功能

用到了@vueuse/core插件的onClickOutside,没有这个插件的 需要npm i @vueuse/core

具体功能看下图:

城市组件的显示隐藏.gif

5 注册使用组件并传值(注意同步数据)

此处忽略组件注册步骤,详细请移步 ===> elementui分页组件底层原理的第五个步骤

以下代码仅供参考

<template>
    <City :fullLocation="fullLocation" @adress-change="hadressChange" />
</template>
<script>
import { ref } from 'vue'
export default {
name: 'GoodName',
  props: {
    goodsData: {
      type: Object,
      default: () => ({})
    }
  },
  setup (props) {
    // 默认情况
    const provinceCode = ref('110000')
    const cityCode = ref('119900')
    const countyCode = ref('110101')
    const fullLocation = ref('北京市 市辖区 东城区')

    // 当前商品中分析出默认地址
    // props.goodsData.userAddresses
    if (props.goodsData.userAddresses && props.goodsData.userAddresses.length > 0) {
      const userAddress = props.goodsData.userAddresses.find(it => it.isDefault === 1)

      provinceCode.value = userAddress.provinceCode
      cityCode.value = userAddress.cityCode
      countyCode.value = userAddress.countyCode
      fullLocation.value = userAddress.fullLocation
    }

    // 从子传递过来的值
    const hadressChange = (adress) => {
      provinceCode.value = adress.provinceCode
      cityCode.value = adress.cityCode
      countyCode.value = adress.countyCode
      fullLocation.value = adress.fullLocation
    }
    return { fullLocation, hadressChange }
  }
}
</script>