I have an array of types, that I am displaying as a list using v-for. When the user clicks on one of the list items, I want to create a new object in the allFields object of that type, meaning that the value in the first key-value pair should be whatever "type" the user clicked on. Is this possible and if not, what is a better way to go about this? Thanks in advance!
<ul>
<li v-for="type in types" @click="addNew">{{ type }}</li>
</ul>
new Vue ({
el: '#app',
data: {
types: [
'date',
'number',
'currency',
'text'
],
allFields: {
}
},
methods: {
addNew: function () {
this.allFields = Object.assign({}, this.allFields, {
field1: {
'type': '?????',
'label': ''
}
});
},
}
});
You should pass an argument to your addNew
function
<ul>
<li v-for="type in types" @click="addNew(type)">{{ type }}</li>
</ul>
new Vue ({
el: '#app',
data: {
types: [
'date',
'number',
'currency',
'text'
],
allFields: {
}
},
methods: {
addNew: function (type) {
this.allFields = Object.assign({}, this.allFields, {
field1: {
'type': type,
'label': ''
}
});
},
}
});
<ul>
<li v-for="(type, key) in types" @click="addNew(key)">{{ type }}</li>
</ul>
new Vue ({
el: '#app',
data: {
types: [
'date',
'number',
'currency',
'text'
],
allFields: {
}
},
methods: {
addNew: function (key) {
this.allFields = Object.assign({}, this.allFields, {
field1: {
'type': this.types[key],
'label': ''
}
});
},
}
});