Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to map the prop's property into Vue's attributes

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

like image 228
刘亚雄 Avatar asked Aug 12 '19 05:08

刘亚雄


2 Answers

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">
like image 56
tony19 Avatar answered Sep 26 '22 16:09

tony19


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" />
like image 34
maxim Avatar answered Sep 22 '22 16:09

maxim