Vue+ElementUI实现简单的用户管理系统(二):axios获取数据、使用table组件显示、vue-router带参数跳转

有了接口和数据后,就要开始获取数据并把它们显示出来了。

(一)axios获取数据

在methods里写一个方法。一开始我没有使用箭头函数而是使用下面这种写法,

 handle(){
        let config = {
          url:'http://localhost:3000/users',
          method: 'get',
        }
        axios(config)
            .then(function(response) {
              this.tableData = response.data
             // console.log(tableData)
            })
      },

然后报错“TypeError: Cannot set property ‘tableData’ of undefined at eval”,于是我改成了:

handle(){
        let config = {
          url:'http://localhost:3000/users',
          method: 'get',
        }
        axios(config)
            .then((response) => {
              this.tableData = response.data
             // console.log(tableData)
            })
      },

为了在界面初始化的时候就得到数据,我在created里调用这个方法:

created() {
      this.handle();
    },

(二)使用ElementUI的table组件展示数据

我参照https://juejin.im/post/5a100d09f265da4324800807 这篇教程
1)新建MyTable.vue组件:

<template>
    <el-table :data="data">
      <template v-for="colConfig in colConfigs">
        <slot v-if="colConfig.slot" :name="colConfig.slot"></slot>
          <el-table-column v-bind="colConfig"></el-table-column>
      </template>
    </el-table>
</template>

<script>
  export default {
    name:'MyTable',
    props: ['colConfigs', 'data']
  }
</script>

2)在父组件中使用:

<template>
  <div class="customers">
    <h1>User Manager System</h1>
    <my-table
      :data="tableData"
      :col-configs="colConfigs">
      <el-table-column slot="opt">
        <el-button size="mini" slot-scope="{ row }" @click="handleClick(row)">查看</el-button>
      </el-table-column>
    </my-table>
  </div>
</template>
data(){
      this.colConfigs = [
        { prop: 'name', label: '姓名' },
        { prop: 'phone', label: '电话' },
        { prop: 'email', label: '邮箱' },
        { slot:"opt"}
      ]
      return {
        tableData:[]
      }
    },

使用这种方法,就可以在列中添加按钮或者其他东西了。在axios的方法中就可以把获取的数据赋值给tableData了。我曾经苦恼于如何在表中显示数据以及如何添加按钮。。。。。。

(三)vue-router带参数跳转

对于如何传Id的值,我苦恼了一阵子。。。。然后我发现在slot-scope里的row里,就有我想要的一切。。。。(应该这个row是包含了这一行的所有信息的吧)

按钮,这个按钮的HTML代码也是复制粘贴官方文档的,那个click方法是我自己加的:

<el-button size="mini" slot-scope="{ row }" @click="handleClick(row)">查看</el-button>

handleClick方法:(我最初是使用params传参的,但是传不过去,咱也不知道什么回事。。。)

 //为什么用params跳转失败?
        // return this.$router.push({
        //   name:'CustomerDetail',
        //   params:{
        //     id:row.id
        //   }
        // })
 handleClick(row){
  
        return this.$router.push({
          path:'/customer',
          query:{
            id:row.id
          }
        })

      },

路由配置:(上面是params的,下面是query的)

{
    path: '/customer/:id',
    name:CustomerDetail,
    component: CustomerDetail,
  },
  {
    path: '/customer',
    name:CustomerDetail,
    component: CustomerDetail,
  },

(四)效果图

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章