问题描述:以change事件为例,在一个循环的标签里插入单选按钮组,改变选项则触发change事件,在某些情况下change方法执行的操作可能需要单选按钮组的索引以便处理不同的操作。
1.elemntui官方单选按钮组组件
<el-radio-group v-model="item.model" @change="changeBarStatus" size="medium">
<el-radio-button label="chartLeft" >启动耗时分布</el-radio-button>
<el-radio-button label="chartRight">启动耗时最差5款</el-radio-button>
</el-radio-group>
<script>
export default {
data(){
return {
barIdModelList: [
{id: 'startTimeEchart', model: 'chartLeft'},
{id: 'cpuUsedEchart', model: 'chartRight'},
{id: 'memUsedEchart', model: 'chartLeft'},
],
}
},
methods: {
changeBarStatus(label) {
console.log(label)//选中的 Radio label 值 'chartLeft'或者'chartRight'
}
}
}
</script>
2. 在循环中插入单选按钮组并传入自定义参数item,index(改进前)
<div class="device-item" v-for="(item, index) in barIdModelList" :key="index">
<div style="margin-top: 20px">
<el-radio-group v-model="item.model" @change="changeBarStatus(label, item, index)" size="medium">
<el-radio-button label="chartLeft" >启动耗时分布</el-radio-button>
<el-radio-button label="chartRight">启动耗时最差5款</el-radio-button>
</el-radio-group>
</div>
<div class="device-charts" :id="item.id">
</div>
</div>
<script>
export default {
data(){
return {
barIdModelList: [
{id: 'startTimeEchart', model: 'chartLeft'},
{id: 'cpuUsedEchart', model: 'chartRight'},
{id: 'memUsedEchart', model: 'chartLeft'},
],
}
},
methods: {
changeBarStatus(label, item, index) {
console.log(label)//undefined
console.log(item)//对应index的item
console.log(index)//当前触发change事件的索引
}
}
}
</script>
通过打印上面的参数发现label为undefined,也就是说选中Radio的label 值并没有传递过来,进行如下改进:
3. 在循环中插入单选按钮组并传入自定义参数item,index(改进后)
<div class="device-item" v-for="(item, index) in barIdModelList" :key="index">
<div style="margin-top: 20px">
<el-radio-group v-model="item.model" @change="((label)=>{changeBarStatus(label, item, index)})" size="medium">
<el-radio-button label="chartLeft" >启动耗时分布</el-radio-button>
<el-radio-button label="chartRight">启动耗时最差5款</el-radio-button>
</el-radio-group>
</div>
<div class="device-charts" :id="item.id">
</div>
</div>
<script>
export default {
data(){
return {
barIdModelList: [
{id: 'startTimeEchart', model: 'chartLeft'},
{id: 'cpuUsedEchart', model: 'chartRight'},
{id: 'memUsedEchart', model: 'chartLeft'},
],
}
},
methods: {
changeBarStatus(label, item, index) {
console.log(label)//对应绑定的label值,'chartLeft'或者'chartRight'
console.log(item)//对应index的item
console.log(index)//当前触发change事件的索引
}
}
}
</script>
以上就是自定义传参的解决办法,其核心就一行代码
@change="((label)=>{changeBarStatus(label, item, index)})"
总结就是以闭包的形式触发函数调用即可