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 App from './App.vue'
Vue.use(ElementUI)
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>
import {getCitys} from '../utils/index'
import {getAreas} from '../utils/index'
export default {
data() {
return {
formData:{
city:'',
area:''
},
cityList:[],
areaList:[]
}
},
created(){
this.renderCityList()
},
methods:{
renderCityList(){
this.cityList=getCitys()
console.log(this.cityList,'citys');
},
renderAreasList(){
this.areaList=getAreas(this.formData.city)
console.log(this.areaList,'areas');
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>