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>

猜你喜欢

转载自blog.csdn.net/risingfine/article/details/83508198