問題場(chǎng)景:
前端常見場(chǎng)景,在表格中嵌套操作按鈕,點(diǎn)擊彈出對(duì)話框dialog,在dialog上有操作提示或者內(nèi)容提交。
注:此處使用element-ui

image
做法:
<el-table-column>
<template slot-scope="scope">
<el-button v-if="scope.row.roomStatus === '0'" slot="reference" class="button" type="danger" size="small" @click="operateDialog(scope.row)">點(diǎn)擊下線</el-button>
<el-button v-else slot="reference" class="button" type="primary" size="small" @click="operateDialog(scope.row)">點(diǎn)擊上線</el-button>
<el-button class="button" type="info" size="small" @click="handleClickDialog(scope.row.roomId)">操作記錄</el-button>
<el-dialog
:title="dialogTitle"
:visible.sync="dialogVisible"
width="30%"
>
<span>請(qǐng)輸入操作原因: </span><br>
<el-input
v-model="dialogTextarea"
type="textarea"
maxlength="100"
show-word-limit
:autosize="{ minRows: 3 }"
/>
<span slot="footer" class="dialog-footer">
<el-button class="button" @click="dialogVisible = false">取消</el-button>
<el-button class="button" type="primary" @click="operateConfirm(scope.row)">提交</el-button>
</span>
</el-dialog>
</template>
</el-table-column>
以上代碼中,在每個(gè)行標(biāo)簽<el-table-column>中,嵌套按鈕,同時(shí)點(diǎn)擊按鈕,彈出對(duì)話框el-dialog,并且使用slot-scope="scope"來(lái)向組件傳遞當(dāng)前行內(nèi)容。
實(shí)測(cè),嵌套dialog時(shí),如果dialog內(nèi)部又有子元素需要取到當(dāng)前行內(nèi)容,scope取值會(huì)發(fā)生錯(cuò)誤,取到當(dāng)前渲染頁(yè)面的最后一行內(nèi)容
原因分析
可能是同時(shí)渲染了所有行的dialog,產(chǎn)生了重疊,實(shí)際取最后一個(gè)(索引值最大)的行內(nèi)容。
但是,上面第一級(jí)嵌套元素button,可以取到正確值。
解決方式
暫時(shí)沒有找到element層面的解決方法。
我用了比較笨的方法,設(shè)置全局變量selectRoom,在第一級(jí)嵌套的時(shí)候的函數(shù)中,修改這個(gè)全局變量值,在dialog二級(jí)嵌套中,直接使用這個(gè)全局變量。
operateConfirm() {
// 全局變量
console.log('selectRoom', this.selectRoom)
if (this.selectRoom.roomStatus === '0') {
this.offlineRoom(this.selectRoom)
} else if (this.selectRoom.roomStatus === '1' || this.selectRoom.roomStatus === '2') {
this.onlineRoom(this.selectRoom)
}
this.dialogVisible = false
},
以上內(nèi)容若有誤,請(qǐng)各位指出,避免誤導(dǎo)更多人。