雖然可以換個思路直接用單選框實現,但是有時候非要用復選框實現單選效果,可能是因為需要復選框的樣式或者別的原因
這里是kettle中SQLFileOutput組件的兩個選項,要實現單選
<el-form :model="row">
<el-col :span="24">
<el-form-item label="增加 創建表 語句">
<el-checkbox v-model="row.createTable" />
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item label="增加 清空表 語句">
<el-checkbox v-model="row.truncateTable" />
</el-form-item>
</el-col>
</el-form>
在vue中可以通過偵聽器watch
來實現單選
watch: {
'row.createTable'() { // 因為數據在表單中,所以需要加上表單名和單引號
this.row.truncateTable = !this.row.createTable
},
'row.truncateTable'() {
this.row.createTable = !this.row.truncateTable
}
},
官方文檔中的例子如下
data: {
question: '',
answer: 'I cannot give you an answer until you ask a question!'
},
watch: {
// 如果 `question` 發生改變,這個函數就會運行
question: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.debouncedGetAnswer()
}
},
但是,這時候產生一個問題就是,第一次選擇之后,后面就會取消不掉,復選框變成必須二選一,可是我們有時候兩個都不想選擇。
所以,在監聽過程中加上判斷,更改之后的代碼如下
'row.createTable'() {
if (this.row.createTable === true) {
this.row.truncateTable = !this.row.createTable
}
},
'row.truncateTable'() {
if (this.row.truncateTable === true) {
this.row.createTable = !this.row.truncateTable
}
}