由于本人实现收藏夹功能时遇到很多问题,故在此发帖记录:
1. 通过:check属性控制多选框动态勾选,但由于VUE特性多选框并不会实时渲染
2. 实现VUE组件实时渲染,可以设置:key="new Date().getTime()"进行强制渲染
3. el-checkbox放缩可以通过定义transform:scale()进行处理
3. 功能说明:
① 若数据库中存在记录,则多选框会动态自动勾选
② 由①所勾选的多选框,取消勾选时会删除数据库对应记录
<!-- 记录弹窗-->
<el-dialog
class="noteDialog"
:append-to-body="true"
:visible.sync="isNoteVisible"
title="添加至记录本"
width="30%"
align-center
>
<div class="content">
<el-form>
<el-form-item
v-for="item in notebook"
:key="item.notebookId"
style="display: block"
>
<el-checkbox
:key="new Date().getTime()"
:checked="isChecked(item.notebookId)"
@change="toUpdateChecked(item.notebookId)"
style="transform: scale(1.3); transform-origin: left"
>{{item.notebookName}}</el-checkbox>
</el-form-item>
</el-form>
</div>
<div class="dialog-footer">
<el-button type="primary" @click="toUpdateNote">确定</el-button>
<el-button type="info" @click="isNoteVisible = false">取消</el-button>
</div>
</el-dialog>
note(){
this.isNoteVisible = true;
this.checked = []; //清空临时存储数组
this.checkedNotebookIds = [];
this.updateChecked = [];
this.updateCheckedIds = [];
this.loadNoteList();
this.searchNote();
},
loadNoteList(){
//从后端获取记题本列表
this.$axios('/api/notebooks').then(res =>{
if(res.data.code == 200) {
this.notebook = res.data.data;
}
}).catch(error =>{
this.$message('获取记题本列表失败!')
})
},
searchNote(){
//查询指定记录本
this.$axios(`/api/noteManages/${this.currentQuestionId}/${this.currentType}`).then(res =>{
this.checked = res.data.data;
this.checkedNotebookIds = this.checked.map(item => item.notebookId);
this.updateCheckedIds = [...this.checkedNotebookIds];
}).catch(error => {
console.error(error);
});
},
isChecked(notebookId){
//动态勾选已有记录本
return this.checkedNotebookIds.includes(notebookId);
},
toUpdateChecked(notebookId) {
//更新勾选的记录本
if (this.updateCheckedIds.includes(notebookId)) {
this.updateCheckedIds = this.updateCheckedIds.filter(id => id !== notebookId);
} else {
this.updateCheckedIds.push(notebookId);
}
console.log(this.updateCheckedIds)
},
toUpdateNote(){
//更新记录情况
let toAdd = this.updateCheckedIds.filter(item => !this.checkedNotebookIds.includes(item));
//记录本新增试题
toAdd.forEach(notebookId =>{
const postData = {
questionId: this.currentQuestionId,
questionType: this.currentType,
notebookId: notebookId
};
this.$axios({
url: '/api/noteManage',
method: 'post',
data: postData
}).then(res => {
if(res.data.code == 200) {
this.$message({
message: '数据添加成功',
type: 'success'
})
}
}).catch(error => {
console.error(error);
});
});
let toDelete = this.checkedNotebookIds.filter(item => !this.updateCheckedIds.includes(item));
//记录本删除试题
toDelete.forEach(notebookId =>{
this.$axios(`/api/noteManage/delete/${this.currentQuestionId}/${this.currentType}/${notebookId}`
).then(res => {
if(res.data.code == 200) {
this.$message({
message: '数据删除成功',
type: 'success'
})
}
}).catch(error => {
console.error(error);
});
});
//关闭弹窗
this.isNoteVisible = false;
},
效果图: