Reputation: 73
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
Upvotes: 6
Views: 4321
Reputation: 626
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" />
Upvotes: 1
Reputation: 138696
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">
Upvotes: 5
Reputation: 61
I would just bind the whole item object in your iteration
<my-li class="ui-draggable-handle"
v-for="(item, index) in deviceList"
:key="index"
:item="item">
</my-li>
Then you're can access the properties of the item inside the component like this
{{ item.subjectId }}
Upvotes: 0
Reputation: 8673
Use computed properties like that
<my-li class="ui-draggable-handle"
:mapping="mappingObject">
Computed object sets all the properties like that
computed: {
mappingObject() {
'appid': 'subjectId',
'apptype': 'appType',
'model': 'subjectModel',
'shortModel': 'shortModel',
'appname': 'subjectName',
'state': 'state',
},
Upvotes: 0