天天看點

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

一. 基礎元件

1. Breadcrumb 面包屑

(1). 效果圖

 點選,首頁,跳轉到首頁。

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

(2). 代碼分享

 通過 separator-class="el-icon-arrow-right"設定分隔符,通過to屬性,進行路由跳轉對象,同 

vue-router

 的 

to

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

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

View Code

2. Card卡片

 這裡采用Card最基本的用法,包裹即可。

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
<el-card >

</el-card>      

3. Input 輸入框 

 這裡采用input标簽作為搜尋框,配合一個button作為右側的搜尋框圖示。如下圖:

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

  使用了下面屬性和事件,同時給搜尋按鈕添加了一個點選事件。

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

 代碼如下:

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
<el-input placeholder="請輸入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>      

PS: input中添加回車事件 @keyup.enter.native="xxx"

<el-input placeholder="請輸入内容" v-model="queryInfo.query" clearable @clear="getGoodsList" @keyup.enter.native="getGoodsList">      

4. Dialog對話框(重點)

(1). 如何控制表格的打開和關閉?

 通過visible.sync屬性來設定表格的打開和關閉,true表示顯示,false表示隐藏,是以打開和關閉都是圍繞這個屬性來處理的。

<el-dialog title="添加使用者" :visible.sync="addDialogVisible" width="600px" @close="addDialogClosed">
      <!-- 内容主體區域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" size="small">
        
      </el-form>
      <!-- 底部區域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
  </el-dialog>      

剖析:

 A. 點選取消按鈕,将 addDialogVisible 設定為false,關閉。

 B. 添加close方法,監聽對話框關閉,用來重置form表單。

// 5.監聽添加使用者對話框的關閉事件
      addDialogClosed() {
        // 表單重置
        this.$refs.addFormRef.resetFields()
      },      

 C. 确定按鈕,走完業務後,也需要将addDialogVisible設定為false,關閉

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

(2). 如何控制彈框高度?

 可以通過width屬性直接設定寬度,但是不能直接設定高度,我們可以給dialog中的内容,比如form表單,外面再包裹一層div,設定這個div的高度即可。

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

(3). 其它

5. Switch開關

 綁定

v-model

到一個

Boolean

類型的變量。可以使用

active-color

屬性與

inactive-color

屬性來設定開關的背景色,通過change事件監控變化。

下面代碼是在表格中使用:

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

6. Select選擇器

用法:

 通過v-model綁定選中後的值,這個值對應的是option中的value,但是顯示出來的是option中的label; clearable屬性增加可删除标記,filterable開啟搜尋。

代碼如下:

<el-select v-model="selectedRoleId" placeholder="請選擇" clearable filterable>
    <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
    </el-option>
 </el-select>      

效果圖:

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

7. MessageBox 彈框

(1). 導入和封裝

 這裡按需導入,和Message元件一樣,不需要use挂載,參考官方的規範,進行簡單的封裝。

import { MessageBox } from 'element-ui';
// Message和MessageBox特殊,不需要use挂載(挂載會出問題)
Vue.prototype.$confirm = MessageBox.confirm      
第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

(2). 基本使用

A. 多次回調的寫法

this.$confirm('此操作将永久删除該檔案, 是否繼續?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });      

B. 同步程式設計寫法

const confirmResult = await this.$confirm('此操作将永久删除該使用者, 是否繼續?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
}).catch(err => err)
   // 如果使用者确認删除,則傳回值為字元串 confirm
   // 如果使用者取消了删除,則傳回值為字元串 cancel
   // console.log(confirmResult)
   if (confirmResult !== 'confirm') {
      return this.$message.info('已取消删除')
   }
//下面執行業務      

8. Form表單

 這裡主要補充自定義驗證規則,和之前章節彙總,詳見:https://www.cnblogs.com/yaopengfei/p/14559280.html

9. Table表格

 結合後續章節的展開列、分頁、自适應等一起介紹。

二. 使用者管理

1. 頁面效果

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理

2. 代碼分享 

第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
第四節:基礎元件(Breadcrumb、Card、Input、Dialog、Switch、Select、MessageBox) 之 使用者管理
<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>

      <!-- 1.搜尋與添加區域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input size="small" placeholder="請輸入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList" size="small"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" @click="addDialogVisible = true">添加使用者</el-button>
        </el-col>
      </el-row>

      <!-- 2.使用者清單區域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="郵箱" prop="email"></el-table-column>
        <el-table-column label="電話" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="時間" prop="create_time">
          <template slot-scope="scope">
            {{scope.row.create_time | dateFormat}}
          </template>
        </el-table-column>
        <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>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按鈕 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按鈕 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">
            </el-button>
            <!-- 配置設定角色按鈕 -->
            <el-tooltip effect="dark" content="配置設定角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 3 分頁區域 -->
      <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>

    </el-card>

    <!-- 三. 添加使用者的對話框 -->
    <el-dialog title="添加使用者" :visible.sync="addDialogVisible" width="600px" @close="addDialogClosed">
      <!-- 内容主體區域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" size="small">
        <el-form-item label="使用者名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密碼" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="郵箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手機" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部區域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 四. 修改使用者的對話框 -->
    <el-dialog title="修改使用者" :visible.sync="editDialogVisible" width="600px" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" size="small">
        <el-form-item label="使用者名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="郵箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手機" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 五.配置設定角色的對話框 -->
    <el-dialog title="配置設定角色" :visible.sync="setRoleDialogVisible" width="450px" @close="setRoleDialogClosed">
      <div>
        <p>目前的使用者:{{userInfo.username}}</p>
        <p>目前的角色:{{userInfo.role_name}}</p>
        <p>配置設定新角色:
          <el-select v-model="selectedRoleId" placeholder="請選擇" clearable filterable>
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {
      // 自定義驗證郵箱的規則
      var checkEmail = (rule, value, cb) => {
        // 驗證郵箱的正規表達式
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          // 合法的郵箱
          return cb()
        }
        cb(new Error('請輸入合法的郵箱'))
      }
      // 自定義驗證手機号的規則
      var checkMobile = (rule, value, cb) => {
        // 驗證手機号的正規表達式
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          return cb()
        }
        cb(new Error('請輸入合法的手機号'))
      }

      return {
        // 擷取使用者清單的參數對象
        queryInfo: {
          query: '',
          // 目前的頁數
          pagenum: 1,
          // 目前每頁顯示多少條資料
          pagesize: 2
        },
        // 表格資料集合
        userlist: [],
        total: 0,
        // 控制添加使用者對話框的顯示與隐藏
        addDialogVisible: false,
        // 添加使用者的表單資料
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 添加使用者的驗證規則對象
        addFormRules: {
          username: [{
              required: true,
              message: '請輸入使用者名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '使用者名的長度在3~10個字元之間',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '請輸入密碼',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 15,
              message: '使用者名的長度在6~15個字元之間',
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '請輸入郵箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '請輸入手機号',
              trigger: 'blur'
            },
            {
              validator: checkMobile,
              trigger: 'blur'
            }
          ]
        },
        // 控制修改使用者對話框的顯示與隐藏
        editDialogVisible: false,
        // 查詢到的使用者資訊對象
        editForm: {},
        // 修改使用者的驗證規則對象
        editFormRules: {
          email: [{
              required: true,
              message: '請輸入使用者郵箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '請輸入使用者手機',
              trigger: 'blur'
            },
            {
              validator: checkMobile,
              trigger: 'blur'
            }
          ]
        },
        // 控制配置設定角色對話框的顯示與隐藏
        setRoleDialogVisible: false,
        // 需要被配置設定角色的使用者資訊
        userInfo: {},
        // 所有角色的資料清單
        rolesList: [],
        // 已選中的角色Id值
        selectedRoleId: ''
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      // 1.加載表格事件
      async getUserList() {
        const {
          data: res
        } = await this.$http.get('users', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          return this.$message.error('擷取使用者清單失敗!')
        }
        this.userlist = res.data.users
        this.total = res.data.total
        console.log(res)
      },
      // 2.監聽 pagesize 改變的事件
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 3.監聽 頁碼值 改變的事件
      handleCurrentChange(newPage) {
        console.log(newPage)
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // 4.監聽 switch 開關狀态的改變
      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.mg_state = !userinfo.mg_state
          return this.$message.error('更新使用者狀态失敗!')
        }
        this.$message.success('更新使用者狀态成功!')
      },
      // 5.監聽添加使用者對話框的關閉事件
      addDialogClosed() {
        // 表單重置
        this.$refs.addFormRef.resetFields()
      },
      // 6.添加新使用者事件
      addUser() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          // 可以發起添加使用者的網絡請求
          const {
            data: res
          } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 200) {
            this.$message.error('添加使用者失敗!')
          }
          this.$message.success('添加使用者成功!')
          // 隐藏添加使用者的對話框
          this.addDialogVisible = false
          // 重新擷取使用者清單資料
          this.getUserList()
        })
      },
      // 7.展示編輯使用者的對話框
      async showEditDialog(id) {
        const {
          data: res
        } = await this.$http.get('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('查詢使用者資訊失敗!')
        }
        this.editForm = res.data
        this.editDialogVisible = true
      },
      // 8.監聽修改使用者對話框的關閉事件
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      // 9.修改使用者資訊并送出
      editUserInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          // 發起修改使用者資訊的資料請求
          const {
            data: res
          } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.meta.status !== 200) {
            return this.$message.error('更新使用者資訊失敗!')
          }
          // 關閉對話框
          this.editDialogVisible = false
          // 重新整理資料清單
          this.getUserList()
          // 提示修改成功
          this.$message.success('更新使用者資訊成功!')
        })
      },
      // 10.根據Id删除對應的使用者資訊
      async removeUserById(id) {
        // 彈框詢問使用者是否删除資料
        const confirmResult = await this.$confirm('此操作将永久删除該使用者, 是否繼續?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 如果使用者确認删除,則傳回值為字元串 confirm
        // 如果使用者取消了删除,則傳回值為字元串 cancel
        // console.log(confirmResult)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        const {
          data: res
        } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除使用者失敗!')
        }
        this.$message.success('删除使用者成功!')
        this.getUserList()
      },
      // 11.顯示配置設定角色的對話框
      async setRole(userInfo) {
        this.userInfo = userInfo
        // 在展示對話框之前,擷取所有角色的清單
        const {
          data: res
        } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('擷取角色清單失敗!')
        }
        this.rolesList = res.data
        this.setRoleDialogVisible = true
      },
      // 12. 監聽配置設定角色對話框的關閉事件
      setRoleDialogClosed() {
        this.selectedRoleId = ''
        this.userInfo = {}
      },
      // 13. 點選按鈕,配置設定角色
      async saveRoleInfo() {
        if (!this.selectedRoleId) {
          return this.$message.error('請選擇要配置設定的角色!')
        }
        const {
          data: res
        } = await this.$http.put(
          `users/${this.userInfo.id}/role`, {
            rid: this.selectedRoleId
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色失敗!')
        }
        this.$message.success('更新角色成功!')
        this.getUserList()
        this.setRoleDialogVisible = false
      }
    }
  }
</script>

<style lang="less" scoped>
  .x1 {}
</style>      

!

  • 作       者 : Yaopengfei(姚鵬飛)
  • 部落格位址 : http://www.cnblogs.com/yaopengfei/
  • 聲     明1 : 如有錯誤,歡迎讨論,請勿謾罵^_^。
  • 聲     明2 : 原創部落格請在轉載時保留原文連結或在文章開頭加上本人部落格位址,否則保留追究法律責任的權利。