there are many attribute I want to set in my component, but the first code is so bloated, I wonder if there is a better solution
<li class="ui-draggable-handle"
v-for="(item, index) in deviceList"
:key="index"
:appid="item.subjectId"
:apptype="item.appType"
:model="item.subjectModel"
:shortModel="item.shortModel"
:appname="item.subjectName"
:state="item.state">
<my-li class="ui-draggable-handle"
:mapping="{
'appid': 'subjectId',
'apptype': 'appType',
'model': 'subjectModel',
'shortModel': 'shortModel',
'appname': 'subjectName',
'state': 'state',
}">
so how can I map the mapping in 's attributes
v-bind
can take an object to bind multiple attributes/props at once. The directive's value could be an object literal:
<li
v-for="(item, index) in deviceList"
v-bind="{
'appid': item.subjectId,
'apptype': item.appType,
'model': item.subjectModel,
'shortModel': item.shortModel,
'appname': item.subjectName,
'state': item.state,
}">
...or an object variable, where only applicable keys are mapped (non-existing attributes/props are ignored):
<li
v-for="(item, index) in deviceList"
v-bind="item">
First of, you can pass properties of an object as component props by binding the entire object, like it's described in the documentation:
<my-li v-bind="item" class="ui-draggable-handle">
Since your component's props do not correspond to the properties of your item object you could pass them like tony19 has suggested in his answer. Though if you want to have your template look cleaner you could use a computed property instead of your original deviceList. like this:
computed: {
deviceListMapped() {
return this.deviceList.map(item => ({appid: item.subjectId, apptype: item.appType, model: item.subjectModel, shortModel: item.shortModel, appname: item.subjectName, state: item.state}))
},
}
Then in your template your iterate through the deviceListMapped and v-bind its' items like this:
<my-li
v-for="(item, i) in deviceListMapped"
:key="i"
v-bind="item" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With