这是一个常见问题。当然,其中很多事情都取决于个人喜好或意见,但这里有一些需要考虑的事情:
通常,在解决此问题时,您会以某种方式(即列表)显示所有现有模型,并带有“编辑”按钮。当我这样做时,我使用一个将模型 ID 映射到其相应模型对象的对象作为该列表的基础数据模型。这使得用更新版本替换模型变得容易(models[model.id] = model
).
直接将模型绑定到表单(例如:model =“您要编辑的模型”)通常是一个糟糕的实现。这是因为编辑期间所做的任何更改都会立即写入模型。问题是,如果你的save()
功能失败,那么你必须把一切都改回来。更好的实现是克隆模型,然后绑定that反对该表格。
您可以将计算属性用于模式的标题/标题。我通常有一个名为的数据属性mode
,这将是“创建”或“编辑”,然后我有一个返回的计算属性mode + ' Model'
,其中“Model”是模型的名称 - 在您的例子中为“Pregunta”。
自从create
and update
函数通常使用不同的 API 端点(和 HTTP 方法),您的“保存/更新”按钮需要调用正确的端点。再次,我使用mode
属性来处理这个问题(例如<button @click="mode == 'edit' ? update : save">
)
下面的代码应该为您提供一个良好的起点,让您拥有一个可用于创建和编辑模型的模态,以及大多数模型的基本结构CRUD https://en.wikipedia.org/wiki/Create,_read,_update_and_delete成分。
<template>
<div>
<template v-for="model in modelsArray">
... <!-- Display your existing models however you want -->
<a href="" @click.prevent="edit(model)">Edit</a>
</template>
<button @click="create">Create New Model</button>
<el-dialog
:title="modalTitle"
:loading="loading"
:visible.sync="dialogFormVisible"
>
<el-form :model="formModel">
...
</el-form>
<span slot="footer">
<el-button type="info" @click="cancel">Cancelar</el-button>
<el-button
type="primary"
:loading="loading"
@click="mode == 'edit' ? update : save"
>
{{ mode }}
</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
mode: '',
dialogFormVisible: false,
loading: false,
formModel: {},
models: { // an object mapping your existing model IDs
1: { id: 1, ...}, // to their corresponding model objects
2: { id: 2, ...},
3: { id: 3, ...},
...
}
},
...,
computed: {
modelsArray() {
return Object.values(this.models);
},
modalTitle() {
return `${ this.mode } Model`;
}
},
methods: {
create() {
this.mode = 'Create';
this.dialogFormVisible = true;
},
edit(model) {
this.mode = 'Edit';
this.formModel = _.cloneDeep(model); // See note below
this.dialogFormVisible = true;
},
save() {
// POST the new model (this.formModel) to your server using your ajax library of choice
// after the ajax call returns, do the following:
this.models.push(the newly created model); // usually returned from the server as part of this ajax call
this.reset();
},
update() {
// PUT the new model (this.formModel) to your server using your ajax library of choice
// After the ajax call returns, replace the updated model in the `models` object, and reset the form:
this.models[this.formModel.id] = _.cloneDeep(this.formModel);
this.reset();
},
reset() {
this.dialogFormVisible = false;
this.loading = false;
this.formModel = {
... // put default form values here
};
}
},
mounted() {
this.reset();
}
}
</script
NOTE: _.cloneDeep https://lodash.com/docs#cloneDeep来自洛达什。如果您不使用 lodash,您可以使用其中之一这些方法 https://stackoverflow.com/a/728694/3109473克隆模型。