Vue + ElementUI的電商管理系統實例03 用戶列表


1、通過路由展示用戶列表頁

新建user文件夾,里面新建Users.vue文件:

<template>
<div>
  <h3>用戶列表組件</h3>
</div>
</template>

<script>
export default {
}
</script>

<style lang="less" scoped>

</style>

修改路由文件,添加Users路由:

import Users from '../components/user/Users.vue'

const routes = [
  { path: '/', redirect: '/login' }, // 重定向
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome', // 重定向
    children: [ // 子路由
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users } // 用戶列表
    ]
  }
]

這時點擊左側菜單的用戶列表,就可以看到跳轉到了用戶列表頁:

2、小bug:刷新后左側菜單的高亮沒有了

Menu Attribute里有個default-active屬性: 表示當前激活菜單的 index,就是說如果想讓菜單中的某一項高亮被激活,就把這項對應的index的值,賦值為整個menu菜單的default-active屬性。

每次點擊左側二級菜單時,把對應的index的值,賦值給default-active屬性。

<el-menu background-color="#333744" text-color="#fff" active-text-color="#409eff" :unique-opened="true"
           :collapse="isCollapse" :collapse-transition="false" :router="true" :default-active="activePath">

<el-menu-item :index="'/' + subItem.path" v-for="subItem in item.children" :key="subItem.id" @click="saveNavState">

<script>
export default {
  data() {
    return {
      activePath: '' // 激活狀態值
    }
  },
  methods: {  
    // 保存菜單鏈接的激活狀態
    saveNavState(item) {
      console.log(item.index)
      this.activePath = item.index
    }
  }
}
</script>

這樣寫完后發現可以實現效果,但是一刷新,激活狀態又沒有了,,准備存到sessioStorage中實現保存:

<el-menu background-color="#333744" text-color="#fff" active-text-color="#409eff" :unique-opened="true"
           :collapse="isCollapse" :collapse-transition="false" :router="true" :default-active="activePath">

<el-menu-item :index="'/' + subItem.path" v-for="subItem in item.children" :key="subItem.id" @click="saveNavState">

<script>
export default {
  data() {
    return {
      activePath: '' // 被激活的鏈接地址
    }
  },
  // 生命周期函數
  created() {
    this.getMenuList()
    this.activePath = window.sessionStorage.getItem('activePath')
  },
  methods: {
    // 保存菜單鏈接的激活狀態
    saveNavState(item) {
      console.log(item.index)
      this.activePath = item.index
      // 將點擊之后的index地址保存到客戶端的sessionStorage中
      window.sessionStorage.setItem('activePath', item.index)
    }
  }
}
</script>

可以實現效果了,刷新后還是高亮的。

后來發現新版Element支持更簡單的寫法了:

<el-menu background-color="#333744" text-color="#fff" active-text-color="#409eff" :unique-opened="true"
           :collapse="isCollapse" :collapse-transition="false" :router="true" :default-active="$route.path">

<!--直接給default-active綁定$route.path的值就可以了-->

3、用戶列表基礎布局

首先要把使用的面包屑和卡片組件添加到element.js里:

import Vue from 'vue'
import { Button, Form, FormItem, Input, Message, Container, Header, Aside, Main,
  Menu, Submenu, MenuItemGroup, MenuItem, Breadcrumb, BreadcrumbItem, Card } from 'element-ui'

Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
Vue.use(Container)
Vue.use(Header)
Vue.use(Aside)
Vue.use(Main)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItemGroup)
Vue.use(MenuItem)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Card)
// 掛載到Vue全局
Vue.prototype.$message = Message

在Users.vue里添加面包屑和卡片代碼:

<template>
  <div>
    <!--面包屑導航區域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首頁</el-breadcrumb-item>
      <el-breadcrumb-item>用戶管理</el-breadcrumb-item>
      <el-breadcrumb-item>用戶列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片視圖區域-->
    <el-card>
      111
    </el-card>
  </div>
</template>

然后在全局樣式global里添加重置樣式:

/* 全局樣式表 */
html, body, #app {height: 100%; margin: 0; padding: 0;}
.el-breadcrumb{margin-bottom: 15px;font-size: 12px;}
.el-card{box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;}

然后進行卡片里的布局,上部是一個搜索框和一個添加按鈕,這個可以用柵格布局,記得把Row, Col添加導入到element.js,這里就不寫了

實現代碼:

<template>
  <div>
    <!--面包屑導航區域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首頁</el-breadcrumb-item>
      <el-breadcrumb-item>用戶管理</el-breadcrumb-item>
      <el-breadcrumb-item>用戶列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片視圖區域-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <!--搜索區域-->
          <el-input placeholder="請輸入內容">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary">添加用戶</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

實現效果:

4、請求接口獲取用戶列表數據

查看接口文檔,1.3.1用戶數據列表:請求路徑是users,請求方式是get,請求參數是:query 查詢參數 可以為空、pagenum 當前頁碼 不能為空、pagesize 每頁顯示條數 不能為空

代碼如下:

<script>
export default {
  data() {
    return {
      userList: [], // 用戶列表
      total: 0, // 用戶總數
      // 獲取用戶列表的參數對象
      queryInfo: {
        query: '', // 查詢參數
        pagenum: 1, // 當前頁碼
        pagesize: 2 // 每頁顯示條數
      }
    }
  },
  created() { // 生命周期函數
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    }
  }
}
</script>

5、使用表格組件渲染用戶列表

首先還是在element.js里添加Table和TableColumn導入:

import Vue from 'vue'
import { Button, Form, FormItem, Input, Message, Container, Header, Aside, Main,
  Menu, Submenu, MenuItemGroup, MenuItem, Breadcrumb, BreadcrumbItem, Card, Row, Col,
  Table, TableColumn } from 'element-ui'

Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
Vue.use(Container)
Vue.use(Header)
Vue.use(Aside)
Vue.use(Main)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItemGroup)
Vue.use(MenuItem)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Card)
Vue.use(Row)
Vue.use(Col)
Vue.use(Table)
Vue.use(TableColumn)
// 掛載到Vue全局
Vue.prototype.$message = Message

然后添加代碼:

<!--用戶列表區域-->
     <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="郵箱"></el-table-column>
        <el-table-column prop="mobile" label="電話"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="狀態"></el-table-column>
        <el-table-column label="操作"></el-table-column>
     </el-table>

邊框:默認情況下,Table 組件是不具有豎直方向的邊框的,如果需要,可以使用border屬性,它接受一個Boolean,設置為true即可啟用。

隔行變色:stripe屬性可以創建帶斑馬紋的表格。它接受一個Boolean,默認為false,設置為true即為啟用。

6、表格前面添加索引列

type="index"

<!--用戶列表區域-->
    <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="郵箱"></el-table-column>
        <el-table-column prop="mobile" label="電話"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="狀態"></el-table-column>
        <el-table-column label="操作"></el-table-column>
    </el-table>

效果圖:

7、自定義狀態列的顯示效果

用到Switch 開關組件,添加導入到element.js,這里就不寫了。

然后要用到作用域插槽:

<!-- 作用域插槽 -->
<template slot-scope="scope">
     {{scope.row}} 
</template>

這里定義了一個作用域插槽,通過slot-scope="scope"接收了當前作用域的數據,然后通過scope.row拿到對應這一行的數據,再綁定具體的屬性值就行了。

<el-table-column prop="mg_state" label="狀態">
     <!-- 作用域插槽 -->
     <template slot-scope="scope">
          <!-- {{scope.row}} -->
          <el-switch v-model="scope.row.mg_state"></el-switch>
     </template>
</el-table-column>

如果同時指定了prop和作用域插槽,那么作用域插槽會覆蓋prop,所以prop就不生效了,可以刪掉。

8、通過作用域插槽自定義操作列

要用過id來操作對應數據,還是定義作用域插槽來實現:

<el-table-column label="操作">
      <!-- 作用域插槽 -->
      <template slot-scope="scope">
            {{scope.row.id}}
      </template>
</el-table-column>

然后要添加三個按鈕組件: size表示尺寸

<!--修改-->
<el-button type="primary" size="mini" icon="el-icon-edit"></el-button>
<!--刪除-->
<el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
<!--分配角色-->
<el-button type="warning" size="mini" icon="el-icon-setting"></el-button>

需要給分配角色按鈕添加一個鼠標移上去有提示信息,使用Tooltip 文字提示組件,添加導入這里就不寫了:

<!--分配角色-->
<el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
     <el-button type="warning" size="mini" icon="el-icon-setting"></el-button>
</el-tooltip>

enterable屬性:表示鼠標是否可進入到 tooltip 中,默認是true開的,需要把它綁定為false,鼠標移到上面提示就消失了。

效果圖:

9、實現分頁效果

Pagination 分頁組件,添加導入這里就不寫了

屬性參數         說明                                                       類型          可選值                                                                默認值
current-page   當前頁數,支持 .sync 修飾符                number     —                                                                       1
page-sizes      每頁顯示個數選擇器的選項設置            number[]   —                                                                       [10, 20, 30, 40, 50, 100]
page-size       每頁顯示條目個數,支持 .sync 修飾符   number    —                                                                       10
total                總條目數                                                 number    —                                                                        —
layout             組件布局,子組件名用逗號分隔             String      sizes, prev, pager, next, jumper, ->, total, slot     'prev, pager, next, jumper, ->, total'

事件名稱           說明                                                    回調參數
size-change      pageSize改變時會觸發                     每頁條數
current-change   currentPage改變時會觸發              當前頁
prev-click  用戶點擊上一頁按鈕改變當前頁后觸發    當前頁
next-click  用戶點擊下一頁按鈕改變當前頁后觸發    當前頁

<!--分頁區域-->
<el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
</el-pagination>

<script>
export default {
  methods: {
     // 監聽 pageSize 改變的事件
    handleSizeChange(newSize) {
       console.log(newSize)
    },
    // 監聽 當前頁碼值 改變的事件
    handleCurrentChange(newPage) {
       console.log(newPage)
    }  
  }
}
</script>

然后把點擊改變后的newSize和newPage,再賦值給回pagesize和pagenum,然后重新獲取用戶列表數據:

// 監聽 pageSize 改變的事件
   handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      // 重新發起請求用戶列表
      this.getUserList()
   },
   // 監聽 當前頁碼值 改變的事件
   handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      // 重新發起請求用戶列表
      this.getUserList()
   }

在添加一個全局的分頁樣式:

/* 全局樣式表 */
html, body, #app {height: 100%; margin: 0; padding: 0;}
.el-breadcrumb{margin-bottom: 15px;font-size: 12px;}
.el-card{box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;}
.el-table{margin-top: 15px;font-size: 12px;}
.el-pagination{margin-top: 15px;}

現在點擊分頁,用戶列表數據就可以隨之變化了。 

效果圖:

10、修改用戶狀態

查看Switch事件:

事件名稱             說明                                         回調參數
change switch    狀態發生變化時的回調函數     新狀態的值

修改代碼,添加事件:

<el-table-column label="狀態">
   <!-- 作用域插槽 -->
   <template slot-scope="scope">
        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
   </template>
</el-table-column>

<script>
export default {
  methods: {
    // 監聽 當前狀態值 改變事件
    userStateChanged(userinfo) {
       console.log(userinfo)
    }
  }
}
</script>

現在就要把修改后的用戶信息保存到服務器。

查看接口文檔,1.3.3. 修改用戶狀態,請求路徑:users/:uId/state/:type,請求方法:put,
請求參數:uId:用戶ID:不能為空`攜帶在url中、type:用戶狀態:不能為空`攜帶在url中`:值為 true 或者 false

修改添加代碼:

// 監聽 當前狀態值 改變事件
   async userStateChanged(userinfo) {
      console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.ms_state = !userinfo.ms_state
        return this.$message.error('更新用戶狀態失敗')
      }
      this.$message.success('更新用戶狀態成功!')
   }
// 注意put這里為了拼接動態參數用的是反引號``

現在點擊修改用戶狀態,再重新刷新后,顯示的還是剛才修改后的狀態,成功。

11、實現搜索功能

給搜索框實現雙向綁定,並添加點擊事件:綁定queryInfo.query,點擊重新獲取用戶列表

<!--搜索區域-->
<el-input v-model="queryInfo.query" placeholder="請輸入內容">
      <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
</el-input>

添加清空按鈕,清空輸入框同時刷新用戶列表:

使用clearable屬性即可得到一個可清空的輸入框

clear事件 在點擊由 clearable 屬性生成的清空按鈕時觸發

<el-input v-model="queryInfo.query" placeholder="請輸入內容" clearable @clear="getUserList">

效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM