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,
  },

(四)效果圖

在這裏插入圖片描述

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