[英]How to create dynamic form in sails.js with vue.js?
我正在使用sails.js 1.0和vue.js,並希望創建一個動態表單,其中包含基於用戶首選項的動態數量的輸入。 因此,用戶應該能夠添加另一個輸入,鍵入數據並發送包含動態數據量的完整表單。
我的表單看起來像這樣:
<ajax-form action="addStuff" :syncing.sync="syncing" :cloud-error.sync="cloudError" @submitted="submittedForm()" :handle-parsing="handleParsingForm">
...
<input class="form-control" id="input1" name="input1" type="text" :class="[formErrors.password ? 'is-invalid' : '']"
v-model.trim="formData.input1" placeholder="Input #1" autofocus>
...
<ajax-button type="submit" :syncing="syncing" class="btn btn-dark">Save changes</ajax-button>
</ajax-form>
addStuff
中的動作addStuff
如下所示:
module.exports = {
friendlyName: 'Do some stuff',
description: 'Do some stuff with the form data.',
inputs: {
input1: {
description: 'The first input.',
required: true
}
},
fn: async function (inputs, exits) {
// Do some stuff with the inputs
return exits.success();
}
};
我知道通常我可以使用vue.js創建動態表單
v-for
循環,然后為數據對象中的每個元素創建一個輸入 但是對於sails和這個ajax-form
,我不知道如何訪問vue實例及其數據元素以及如何使其在動作中也是動態的。 顯然輸入需要包含一個數組。
如何實現這種動態形式?
我想出了缺失的部分。 Sails.js使用滑翔傘這是建立在vue.js.的頂部
當使用sails generator sails new test-project
生成新的sails頁面時,還會生成一個聯系表單,其中還包含可用於此目的的必要代碼。
該聯系表格基本上由
contact.page.js
客戶端腳本 deliver-contact-form-message.js
在客戶端腳本中,可以設置初始formData
:
parasails.registerPage('maindivid', {
// ╦╔╗╔╦╔╦╗╦╔═╗╦ ╔═╗╔╦╗╔═╗╔╦╗╔═╗
// ║║║║║ ║ ║╠═╣║ ╚═╗ ║ ╠═╣ ║ ║╣
// ╩╝╚╝╩ ╩ ╩╩ ╩╩═╝ ╚═╝ ╩ ╩ ╩ ╩ ╚═╝
data: {
// Main syncing/loading state for this page.
syncing: false,
// Form data
formData: { /* … */ },
// For tracking client-side validation errors in our form.
// > Has property set to `true` for each invalid property in `formData`.
formErrors: { /* … */ },
// Server error state for the form
cloudError: '',
// Success state when form has been submitted
cloudSuccess: false,
},
...
以及方法等
它遵循與普通vue.js類似的結構。
為了實現我想要做的事情,我將一個字段作為數組添加到formData
formData: {
myinputs: [
{
key: '',
value: ''
}
]
},
然后我將其綁定在.ejs文件中:
<div class="form-row" v-for="(filter, index) in formData.mypinputs">
<input class="form-control form-control-sm" type="text" :class="[formErrors.password ? 'is-invalid' : '']"
v-model.trim="formData.myinputs[index].key" placeholder="My field">
<button type="button" class="btn btn-secondary btn-sm" @click="addFilterForm">add field</button>
</div>
最后,在用戶單擊“添加字段”按鈕時調用contact.page.js
(或您的名字)中的客戶端腳本添加了一個方法。
methods: {
addFilterForm: function() {
this.formData.myinputs.push({
key: '',
value: ''
});
},
由於雙向綁定,只要將元素添加到數組formData.myinputs
,就會創建另一個輸入並將其添加到DOM。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.