本節將進一步將表單封裝成類。首先,定義基本的類:html
class Form { constructor(data) { this.originData = data; //form.data.name for (let field in data) { this[field] = data[field]; // form.name } this.errors = new Errors(); } }
爲了能夠經過 form.name
的方式來訪問字段,所以使用 for
循環來對屬性進行賦值。ios
因爲表單的數據以及錯誤消息如今都經過 form
實例來訪問,所以其餘地方也要對應做出修改。axios
onSubmit(){ this.$http.post('/tasks',this.$data) .catch(error => this.form.errors.record(error.response.data)); },
視圖部分也要響應做出更改:post
<form method="POST" action="/tasks" @submit.prevent="onSubmit" @keydown="form.errors.clear($event.target.name)"> <fieldset class="form-group"> <label for="name">任務名</label> <input type="text" class="form-control" id="name" name="name" v-model="form.name"> <small class="text-danger" v-if="form.errors.has('name')" v-text="form.errors.get('name')"></small> </fieldset> <fieldset class="form-group"> <label for="description">任務描述</label> <input type="text" class="form-control" id="description" name="description" v-model="form.description"> <small class="text-danger" v-if="form.errors.has('description')" v-text="form.errors.get('description')"></small> </fieldset> <button type="submit" class="btn btn-primary" :disabled="form.errors.any()">建立</button> </form>
接下來將表單的其餘請求都封裝到 Form
中。完整的 Form
類以下this
class Form { /** * 數據初始化 */ constructor(data) { this.originalData = data; //form.data.name for (let field in data) { this[field] = data[field]; // form.name } this.errors = new Errors(); } /** * 重置表單 */ reset(){ for (let field in this.originalData) { this[field] = ''; } this.errors.clear(); } /** * 返回表單數據 * @return {[type]} [description] */ data(){ let data = {}; for (let property in this.originalData) { data[property] = this[property]; } return data; } post(url) { return this.submit('post', url); } put(url) { return this.submit('put', url); } patch(url) { return this.submit('patch', url); } delete(url) { return this.submit('delete', url); } submit(requestType, url) { return new Promise((resolve, reject) => { axios[requestType](url, this.data()) .then(response => { this.onSuccess(); resolve(response.data); }) .catch(error => { this.onFail(error.response.data); reject(error.response.data); }); }); } onSuccess(data) { this.reset(); } onFail(errors) { this.errors.record(errors); } }
使用url
onSubmit(){ this.form.post('/tasks') .then(message => alert(message)) .catch(message => console.log(message)); }