封装城市和区域输入框的组件

312 阅读1分钟

1、项目准备工作

  • vue create 项目名称
  • cd 项目名称
  • npm run serve
  • npm i element-ui

2、main.js 引入 element-ui 并使用插件

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// import locale from 'element-ui/lib/locale/lang/en'
import App from './App.vue'

Vue.use(ElementUI)
// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })

new Vue({
  el: '#app',
  render: h => h(App)
})

3、新建 src/utils/index.js (准备城市区域的数据)

// ◆城市对应的区域数据
const datas=[
    {
        city: '武威市',
        area: ['凉州区', '民勤县', '古浪县', '天祝藏族自治县']
      },
      {
        city: '张掖市',
        area: ['甘州区', '肃南裕固族自治县', '民乐县', '临泽县', '高台县', '山丹县']
      },
      {
        city: '平凉市',
        area: ['崆峒区', '泾川县', '灵台县', '崇信县', '华亭县', '庄浪县', '静宁县']
      }
]

// ◆返回所有的城市(导出)
export const getCitys = () => {
    return datas.map(item => {
      return item.city
    })
  }
  
// ◆返回城市下的地区(导出)
 export const getAreas = pname => {
    for (const item of datas) {
      if (item.city === pname) {
        return item.area
      }
    }
    return []
  }

4、新建 src/components/CityArea.vue 子组件

<template>
  <div>
    <el-form :model="formData">
         <el-select v-model="formData.city" placeholder="请选择城市" @change="renderAreasList">
           <el-option v-for="(item,index) in cityList" :key="index" :label="item" :value="item"></el-option>
         </el-select>
         <el-select v-model="formData.area" placeholder="请选择区域">
           <el-option v-for="(item,index) in areaList" :key="index" :label="item" :value="item"></el-option>
         </el-select>
    </el-form>
  </div>
</template>

<script>
// 导入封装好的城市函数 getCitys
import {getCitys} from  '../utils/index'
// 导入封装好的区域函数 getAreas
import {getAreas} from  '../utils/index'
  export default {
    data() {
      return {
        formData:{//表单绑定数据
          city:'',
          area:''
        },
        cityList:[],//城市列表
        areaList:[] //区域列表
      
      }
    },
    created(){
      // 一进页面就触发 methods 中城市列表的渲染
      this.renderCityList()
    },
    methods:{
      // ◆渲染城市列表函数
      renderCityList(){
        // 1.赋值给城市列表
        this.cityList=getCitys()
        console.log(this.cityList,'citys');
      },
      // ◆渲染区域列表函数(城市选择框的 change 事件触发,区域才触发)
      renderAreasList(){
        // 1.赋值给城市对应的区域列表
        this.areaList=getAreas(this.formData.city)
        console.log(this.areaList,'areas');
        // 2.区域一定要清空,防止客户修改城市,区域仍显示上一次的数据
        this.formData.area=''
      }
    }
  }
</script>

5、app.vue 里面局部注册使用(也可以全局注册、批量注册等)

<template>
  <div>
    <!-- 使用城市区域组件 -->
    <CityArea></CityArea>
  </div>
</template>

<script>
// 导入城市区域组件
import CityArea from  './components/CityArea.vue'
export default {
  // 注册城市区域组件
  components:{
    CityArea
  }
}
</script>