vue v-for dynamic properties

UI 畫table,v-for欄位名稱不hard code,dynamic撰寫

by cactus77kiki

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  
  {{titles}}<br/>
  <!--取得物件內屬性title值=>array-->
  <!--{{titles.map(a => a.title)}}<br/>-->
  <input type="text" width="250px;" v-model="xlsxtitle"/>
  <br/>
  <table >
    <thead>
      <th v-for="item in titles">
        {{item}}
      </th>
      <!--<th>學號</th>
      <th>姓名</th>
      <th>數學</th>
      <th>國文</th>-->
    </thead>
    <tbody>
      <tr v-for="(row,index) in xlsxdata">
        <td v-for="title in titles">{{row[title]}}</td>
        <!--<td>{{row.學號}}</td>
        <td>{{row.姓名}}</td>
        <td>{{row.數學}}</td>
        <td>{{row.國文}}</td>-->
      </tr>
    </tbody>
  </table>
</div>

CSS

table, th, td {
  border: 1px solid black;
}

JavaScript

/*
ref: https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array  (array.map)
ref: https://flaviocopes.com/how-to-remove-last-char-string-js/  (slice)
*/
var app = new Vue({
	el:'#app',
  data: {
    xlsxtitle: '學號,姓名,數學,國文',
    xlsxdata: [
    	{ '學號': '1', '姓名': 'John', '數學': 60, '國文': 92 },
      { '學號': '2', '姓名': 'Marry', '數學': 64, '國文': 70 },
      { '學號': '3', '姓名': 'Sala', '數學': 50, '國文': 72 },
      { '學號': '4', '姓名': 'Bibi', '數學': 70, '國文': 66 },
      { '學號': '5', '姓名': 'Ulala', '數學': 40, '國文': 88 },
      { '學號': '6', '姓名': 'Rita', '數學': 75, '國文': 44 },
      { '學號': '7', '姓名': 'Qoo', '數學': 82, '國文': 74 },
      { '學號': '8', '姓名': 'Wing', '數學': 90, '國文': 64 },
      { '學號': '9', '姓名': 'Zebra', '數學': 33, '國文': 87 },
      { '學號': '10', '姓名': 'Dingdon', '數學': 67, '國文': 65 },
    ],
  },
  computed: {
  	titles: function(){	//xlsx title object
    	if(this.xlsxtitle.length >0){
      	//將尾端的逗號刪除
      	let valuer = this.xlsxtitle;
      	if (valuer.slice(-1) == ',') valuer = valuer.slice(0,-1);
      	return valuer.split(',');
      }else
      	return [];
    },
    
  },
  methods: {                                
  	
  }
});