我正在尝试动态创建一个表单(为什么?它有200多个字段,并且不允许修改它)。整个应用程序都在VueJs环境中。
我遇到的问题是(显然)每个字段需要不同的东西。我正在尝试向每个字段动态添加属性,这将允许我动态呈现整个表单,而不是硬编码200多个字段表单。因此,愚蠢的是,我花了更多的时间来尝试解决此问题,而不仅仅是硬编码表单。哦,好吧...
这是我要执行的操作的特定(简化)示例...
data() {
return {
form: {
input1: {value: "", classIWantToDynamicallyAdd: "FieldSizeSmallAF"},
input2: {value: "", classIWantToDynamicallyAdd: "FieldSizeBigAF"},
//Repeat 200 times
}
}
}
现在,我最终要获得“ classIWantToDynamicallyAdd”的值并:class =“ 放在这里”
HTML看起来像这样:
<template>
<div>
<div v-for="(field, index)" in form" :key="index">
<div class="labelAndInput" :class="**I don't know what to do here**">
<label>index</label> // Successfully outputs: "input1", "input2", etc...
<input>
</div>
</div>
</div>
</template>
希望这很清楚。我希望form.index.classIWantToDynamicallyAdd
可以正常工作,但是没有成功,出现以下错误:
TypeError:“ _ vm.form.index未定义”。
谢谢!
答案 0 :(得分:1)
您可以做:class="[field.classIWantToDynamicallyAdd]"
:
<div v-for="(field, index)" in form" :key="index">
<div class="labelAndInput" :class="[field.classIWantToDynamicallyAdd]">
....
<input>
</div>
</div>
答案 1 :(得分:0)
您可以在data()上定义那些类名,然后将其绑定到:class
示例: https://jsfiddle.net/pguti19/hL2vamnw/
更多帮助: https://michaelnthiessen.com/dynamically-add-class-name/
<div id="app">
<h1>
Forms:
</h1>
<div v-for="(field, index) in form" :key="index">
<span :class="field.class">
Using {{field.class}} class
</span>
</div>
</div>
<script>
new Vue({
el: "#app",
data: {
form: {
input1: {value: "", class: "red-theme"},
input2: {value: "", class: "blue-theme"},
input3: {value: "", class: "green-theme"}
},
theme1: 'blue-theme',
theme2: 'red-theme',
theme3: 'green-theme'
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
</script>