I have a form that has many fields. Depending on the type selected by the user some fields should be visible or not visible. I want to use computed properties to conditionally show and hide the fields, but I do not want to code each property as there are many. I’d rather programmatically create the computed properties from an array of field names. My attempt to do this is below but did not work. What am I doing wrong?
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.9/vue.js"></script>
<html>
<div id="app">
<select v-model="type">
<option v-for="option in options" :value="option.value">
{{ option.text }}
</option>
</select>
<p>showA: {{ showA }}</p>
<p>showB: {{ showB }}</p>
<p>showC: {{ showC }}</p>
<p>dynamicShowA: {{ dynamicShowA }}</p>
<p>dynamicShowB: {{ dynamicShowB }}</p>
<p>dynamicShowC: {{ dynamicShowC }}</p>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
message: 'Hello World!',
type: 'Type1',
options: [
{ text: 'Type1', value: 'Type1' },
{ text: 'Type2', value: 'Type2' },
],
fieldLists: {
'Type1': ['A', 'C'],
'Type2': ['B', 'C'],
},
fields: ['A', 'B', 'C'],
}
},
computed: {
selectedFields() {
return this.fieldLists[this.type]
},
showA() {
return this.selectedFields.includes('A')
},
showB() {
return this.selectedFields.includes('B')
},
showC() {
return this.selectedFields.includes('C')
},
},
created() {
for (let field of this.fields) {
this.addProp(field, () => { this.selectedFields.includes(field) })
}
},
methods: {
addProp (fieldName, getter) {
const propName = `dynamicShow${fieldName}`
const computedProp = {
get() {
return getter()
}
}
this[propName] = computedProp
},
}
});
</script>
</html>