使用 Vue.js 和 Vue CLI 3 处理一些处理后通过道具渲染项目

Rendering items via props after handling some processing using Vue.js and Vue CLI 3

我有一个名为 App.vue 的主要组件和一个包含 MyTable.vue 的子组件41=] 的数据,只显示前 10 行,我正在使用 vue cli 3,当我 运行 npm run serve 命令并转到给定地址时,它只呈现 head 我的 table,但是当我在 MyTable.vue 内的 mounted() 函数中添加一些代码时,就像 console.log() 它也呈现了我的 table,当我刷新我的页面时,问题又来了,我该如何处理?

这些是我的组件

App.vue

<template>
  <div class="main-page">     
    <my-table title="todos" :cols="todo_attr" :rows_data="todo_data"></my-table>        
 </div>
</template>
<script>

import MyTable from './components/MyTable.vue'
import todos from './assets/todos.json'
export default {
  name: 'app',
  data(){
return{
  todo_attr:[
    "todoId","id","title","completed"
  ],
     todo_data:[]   
}
  },
  components: {
    MyTable
  },
  mounted(){this.todo_data=todos;}
}
</script>

MyTable.vue

<template>
<div class="vet-container">
    <table>
        <thead>
            <th class="tab-head-cell" v-for="col in cols" :key="col">{{col}}</th>
        </thead>
        <tbody>
            <tr class="tab-rows_data-row" v-for="row in currentPageData" :key="row.id">
                <td class="tab-rows_data-cell" v-for="(cell,key,index)  in row" :key="key+index" > {{cell}}</td>
            </tr>
        </tbody>
    </table>
</div>
</template>

<script>
export default {
    name: 'my-table',
    props: {
        title: String,
        cols: {},
        rows_data: {}

    },
    data() {
        return {
            currentPageData: {}
        };
    },
    methods:{
        createFirstPage(){    
          this.currentPageData = this.rows_data.slice(0, 10);
        }
    }
    ,
    mounted() {
     this.createFirstPage();
    }
}
</script>

首先,您在 MyTable.vue 中将 colsrows_data 声明为对象,但在 App.vue 中将它们声明为数组。您还将 currentPageData 声明为对象而不是数组。这可能会导致一些错误。

其次,您应该更喜欢这样做:

<template>
  <div class="vet-container">
  <table>
    <thead>
    <th class="tab-head-cell" v-for="col in cols" :key="col">{{col}}</th>
    </thead>
    <tbody>
    <tr class="tab-rows_data-row" v-for="row in currentPageData" :key="row.id">
      <td
      class="tab-rows_data-cell"
      v-for="(cell,key,index)  in row"
      :key="key+index" >{{cell}}</td>
    </tr>
    </tbody>
  </table>
  </div>
</template>

<script>
export default {
  name: 'my-table',
  props: {
    title: String,
    cols: Array,
    rows_data: Array,
  },
  data() {
    return {
      index: 0,
      size: 10,
    };
  },
  computed: {
    currentPageData() {
      const start = this.index * this.size;
      const end = start + this.size;
      return this.rows_data.slice(start, end);
    },
  },
};
</script>

然后您可以在 props 中传递索引并在单击按钮时在父项上更改它。

computed 属性 的一点解释:这个 属性 就像计算的 data 一样。您可以像使用任何其他 dataprops 一样使用它,并且可以根据其他内容计算其内容,例如此处,使用当前索引和页面大小。