gpt4 book ai didi

javascript - vue.js/javascript新建对象onclick,其中一个值为你点击的列表项的值

转载 作者:行者123 更新时间:2023-11-30 14:41:44 25 4
gpt4 key购买 nike

我有一个类型数组,我使用 v-for 将其显示为列表。当用户单击其中一个列表项时,我想在该类型的 allFields 对象中创建一个新对象,这意味着第一个键值对中的值应该是用户单击的任何“类型”。这可能吗?如果不可能,有什么更好的方法来解决这个问题?提前致谢!

<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': ''
}
});
},
}
});

最佳答案

您应该将参数传递给您的addNew 函数

传递值

<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': ''
}
});
},
}
});

传递 key

<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': ''
}
});
},
}
});

关于javascript - vue.js/javascript新建对象onclick,其中一个值为你点击的列表项的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49530453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com