需要使用区域,区域和位置的选择选项来帮助创建动态搜索表单。 选择的地区必须根据地区和地区填写,
数据存储在具有以下结构的JSON文件中:
[
{
"level": 1,
"code": 1,
"name": "District"
},
{
"level": 2,
"code": 101,
"name": "Region"
},
{
"level": 3,
"code": 10101,
"name": "Location"
}
]
这是完整的JSON文件: https://gist.github.com/tomahock/a6c07dd255d04499d8336237e35a4827
<select name="district" v-model="district">
<option value=''>Select District</option>
<option v-for="district in filterDistricts" :value="district.code">
{{ district.name }}
</option>
</select>
<select name="region" v-model="region">
<option value=''>Select Region</option>
<option v-for="region in filterRegions" :value="region.code">
{{ region.name }}
</option>
</select>
<select name="location" v-model="location">
<option value=''>Select Location</option>
<option v-for="location in filterLocations" :value="location.code">
{{ location.name }}
</option>
</select>
data() {
return {
searchData: [],
districts: [],
regions: [],
locations: []
}
},
created(){
this.fetchData();
},
computed: {
filterDistricts() {
return this.districts = this.searchData.map(res => ({
level: res.level,
code: res.code,
name: res.name
}))
.filter( res => res.level === 1)
},
filterRegions() {
return this.regions = this.searchData.map(res => ({
level: res.level,
code: res.code,
name: res.name
}))
.filter( res => res.level === 2)
},
filterLocations() {
return this.locations = this.searchData.map(res => ({
level: res.level,
code: res.code,
name: res.name
}))
.filter( res => res.level === 3)
}
},
methods: {
fetchData(){
axios.get('http://localhost:8000/json/searchData.json')
.then((response) => (
this.searchData = response.data
))
.catch((err) => {
console.log(err)
})
}
}
我认为我需要关联代码号,但是我不知道怎么做。
有什么想法吗?
谢谢
答案 0 :(得分:0)
首先,我不会打扰那些map
调用,因为您只在复制相同的结构。
第二,我假设每个子元素(区域/位置)通过一种模式与每个父元素(区域/区域)相关,每个子元素的code
都以父代码为前缀,后跟两个位,零填充。
请牢记这一点,请在您的computed
属性中尝试一下
filterDistricts () {
return this.searchData.filter(({ level }) => level === 1)
},
filterRegions () {
// assuming you don't want any selections until a district is chosen
if (!this.district) return []
const codeCheck = new RegExp(`^${this.district}\\d{2}$`)
return this.searchData.filter(({ level, code }) =>
level === 2 && codeCheck.test(code))
},
filterLocations () {
if (!this.region) return []
const codeCheck = new RegExp(`^${this.region}\\d{2}$`)
return this.searchData.filter(({ level, code }) =>
level === 3 && codeCheck.test(code))
}
额外注释...
通过查看模板,您似乎应该将data
初始化为
data () {
return {
searchData: [],
district: null,
region: null,
location: null
}
}
计算出的属性不需要存储在数据属性中,因此您不需要districts
,regions
和locations
。
您的 label 选项也应该被禁用,以便不能选择它们,例如
<option disabled value="">Select Region</option>