1 问题背景
页面有一组单选按钮类型(A、B、C和D),控制下面的名称下拉框,如果选择类型A,下拉框筛选出type='A'的数据,其他的同理。
2 实现源码
2.1 组件Sa
<template>
<el-row :gutter="20">
<el-col :span="5">
<el-form ref="dataForm" :model="dataForm">
<el-form-item label="类型" prop="type">
<el-radio-group ref="radios" v-model="dataForm.type" @change="changeType">
<el-radio :label="1">A</el-radio>
<el-radio :label="2">B</el-radio>
<el-radio :label="3">C</el-radio>
<el-radio :label="4">D</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="名称">
<el-select v-model="dataForm.username">
<el-option v-for="item in dataForm.options" :key="item.value" :label="item.label" :value="parseInt(item.value)"></el-option>
</el-select>
</el-form-item>
</el-form>
</el-col>
</el-row>
</template>
<script>
export default {
name: 'Sa',
data() {
return {
dataForm: {
type: 1,
username: '',
options:[],
option:[{
label: 'AAA',
value: '2019001',
type: 'A'
},{
label: 'AAB',
value: '2019002',
type: 'A'
},{
label: 'AAC',
value: '2019003',
type: 'A'
},{
label: 'AAD',
value: '2019004',
type: 'A'
},{
label: 'BBA',
value: '2019005',
type: 'B'
},{
label: 'BBB',
value: '2019006',
type: 'B'
},{
label: 'BBC',
value: '2019007',
type: 'B'
},{
label: 'BBD',
value: '2019008',
type: 'B'
},{
label: 'CCA',
value: '2019009',
type: 'C'
},{
label: 'CCB',
value: '2019010',
type: 'C'
},{
label: 'CCC',
value: '2019011',
type: 'C'
},{
label: 'CCD',
value: '2019012',
type: 'C'
},{
label: 'DDA',
value: '2019013',
type: 'D'
},{
label: 'DDB',
value: '2019014',
type: 'D'
},{
label: 'DDC',
value: '2019015',
type: 'D'
},{
label: 'DDD',
value: '2019016',
type: 'D'
}]
}
}
},
mounted() {
this.filterData('A')
},
methods:{
changeType(val) {
this.dataForm.username = ''
var txt = this.$refs.radios.$children[val-1].$el.innerText
console.log(txt)
this.filterData(txt)
},
filterData(params){
let options = this.dataForm.option
let res = []
for (let i = 0; i < options.length; i++) {
if(params == options[i].type){
res.push(options[i])
}
}
this.dataForm.options = res
}
}
}
</script>
<style>
</style>
2.2 路由配置
import Vue from 'vue'
import Router from 'vue-router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import Sa from '@/components/example/Sa'
Vue.use(Router)
Vue.use(ElementUI)
export default new Router({
routes: [
{
path: '/',
name: 'Sa',
component: Sa
}
]
})
3 实现效果
3.1 选择类型A

选择类型A
3.2 选择类型B

选择类型B
3.3 选择类型C

选择类型C
3.4 选择类型D

选择类型D
4 问题难点
4.1 获取单选按钮的文字值
在ElementUI中,获取单选按钮的值(value)是很容易的,但是获取对应的文字值就有点麻烦,需要研究一下单选按钮的相关方法和属性;可以利用原生JS的方法获取innerText,需要打开浏览器控制台进行调试,找到对应的方法和属性。
4.2 对下拉框数据进行过滤
在选择类型A时,下拉框的数据源也要跟着改变,即将type为A的对象值过滤出来,然后装载到新数组里
4.3 下拉框数据源和原始数据
绑定下拉框的options和原始数据option不能使用同一变量,否则就达到不了这个效果
网友评论