1. 程式人生 > >Vue 動態生成資料欄位

Vue 動態生成資料欄位

1.父元件定義data裡面的資料欄位,非同步請求獲取資料(一種配置資料,一種實際資料)

data () {
  return {
    config: [],
    list: []
  };
}

2.子元件接收資料

props: {
  config: Array,
  list: Array
},
data () {
  return {
    newConfig: [],
    configLength: 0,
    newList: []
  };
}

3.因為獲取資料是非同步操作,因此需要監聽資料變化,當有資料時展示子元件

configLoaded: false,
listLoaded: false

  定義上面兩個變數來判斷資料是否載入完成,在非同步獲取完資料後賦值為true,並監聽

watch: {
  configLoaded (n, o) {
        this.configLoaded = n;
  },
  listLoaded (n, o) {
    this.listLoaded = n;
  }
},

4.計算屬性計算兩個變數是否均完成,並執行v-if

computed: {
  showItem () {
    return this.configLoaded && this.listLoaded;
  }
},
<list-item :config="config" :list="list" v-if="showItem"></list-item>

5.子元件完整程式碼

<template>
  <div>
    <div class="item iconfont border-bottom" v-for="(item,index) of newList" :key="index">
      <p v-for="(m,i) of item" :key="i">{{m.name}} {{m.text}}</p>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Item',
    props: {
      config: Array,
      list: Array
    },
    data () {
      return {
        newConfig: [],
        configLength: 0,
        newList: []
      };
    },
    mounted () {
      this.toConfig();
    },
    methods: {
      toConfig () {
        this.configLength = this.config.length;
        for (let i in this.config) {
          let configItem = this.config[i];
          this.newConfig.push({name: configItem.fieldName, text: configItem.fieldDesc});
        }
        for (let l in this.list) {
          let item = this.list[l];
          let childList = [];
          for (var c in this.newConfig) {
            let config = this.newConfig[c];
            for (let key in item) {
              if (config.name === key) {
                childList.push({name: config.text, text: item[key]});
              }
            }
          }
          this.newList.push(childList);
        }
      }
    }
  };
</script>

<style lang="stylus" ref="stylesheet/stylus">
</style>