問題描述:以change事件為例授艰,在一個(gè)循環(huán)的標(biāo)簽里插入單選按鈕組败砂,改變選項(xiàng)則觸發(fā)change事件赌渣,在某些情況下change方法執(zhí)行的操作可能需要單選按鈕組的索引以便處理不同的操作。
1.elemntui官方單選按鈕組組件
<el-radio-group v-model="item.model" @change="changeBarStatus" size="medium">
<el-radio-button label="chartLeft" >啟動(dòng)耗時(shí)分布</el-radio-button>
<el-radio-button label="chartRight">啟動(dòng)耗時(shí)最差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. 在循環(huán)中插入單選按鈕組并傳入自定義參數(shù)item昌犹,index(改進(jìn)前)
<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" >啟動(dòng)耗時(shí)分布</el-radio-button>
<el-radio-button label="chartRight">啟動(dòng)耗時(shí)最差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)//對(duì)應(yīng)index的item
console.log(index)//當(dāng)前觸發(fā)change事件的索引
}
}
}
</script>
通過打印上面的參數(shù)發(fā)現(xiàn)label為undefined,也就是說選中Radio的label 值并沒有傳遞過來斜姥,進(jìn)行如下改進(jìn):
3. 在循環(huán)中插入單選按鈕組并傳入自定義參數(shù)item鸿竖,index(改進(jìn)后)
<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" >啟動(dòng)耗時(shí)分布</el-radio-button>
<el-radio-button label="chartRight">啟動(dòng)耗時(shí)最差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)//對(duì)應(yīng)綁定的label值,'chartLeft'或者'chartRight'
console.log(item)//對(duì)應(yīng)index的item
console.log(index)//當(dāng)前觸發(fā)change事件的索引
}
}
}
</script>
以上就是自定義傳參的解決辦法缚忧,其核心就一行代碼
@change="((label)=>{changeBarStatus(label, item, index)})"
總結(jié)就是以閉包的形式觸發(fā)函數(shù)調(diào)用即可