Vue + ElementUI的電商管理系統實例13 商品列表


1、創建goods_list分支並推送到遠程

創建分支goods_list,並切換到當前:

git checkout -b goods_list

推送到遠程:(以前碼雲中沒有該分支,所以要加-u,如果碼雲中有該分支,則不需要加-u)

git push -u origin goods_list

2、通過路由加載商品列表組件

在goods文件夾和Params.vue文件:

<template>
<div>
  <h3>商品列表組件</h3>
</div>
</template>

<script>
export default {

}
</script>

<style lang="less" scoped>

</style>

添加路由:

import List from '../components/goods/List.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 }, // 用戶列表
      { path: '/rights', component: Rights }, // 權限列表
      { path: '/roles', component: Roles }, // 角色列表
      { path: '/categories', component: Cate }, // 商品分類
      { path: '/params', component: Params }, // 分類參數
      { path: '/goods', component: List } // 商品列表
    ]
  }
]

添加基本布局:

<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="8">
          <!--搜索區域-->
          <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>

點擊左側菜單的商品列表的效果如圖:

3、獲取商品列表數據

調用api的商品列表數據接口,請求路徑:goods,請求方法:get
請求參數:
query 查詢參數 可以為空
pagenum 當前頁碼 不能為空
pagesize 每頁顯示條數 不能為空

添加代碼:

<script>
export default {
  data() {
    return {
      // 獲取商品列表的參數對象
      queryInfo: {
        query: '', // 搜索查詢參數
        pagenum: 1, // 當前頁碼
        pagesize: 10 // 當前每頁顯示條數
      },
      goodsList: [], // 商品列表
      total: 0 // 商品總數
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 根據分頁獲取對應的商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('獲取商品列表失敗')
      }
      this.goodsList = res.data.goods
      this.total = res.data.total
    }
  }
}
</script>

4、渲染商品表格數據

添加表格代碼:

<!--商品表格區域-->
<el-table :data="goodsList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="goods_name" label="商品名稱" ></el-table-column>
        <el-table-column prop="goods_price" label="商品價格(元)" width="95px"></el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" width="70px"></el-table-column>
        <el-table-column prop="add_time" label="創建時間" width="140px"></el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <!--修改按鈕-->
            <el-button type="primary" size="mini" icon="el-icon-edit"></el-button>
            <!--刪除按鈕-->
            <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
</el-table>

此時效果圖:

5、自定義格式化時間的全局過濾器

在main.js里添加代碼:

// 格式化時間的過濾器
Vue.filter('dateFormat', function(originVal) {
  const dt = new Date(originVal * 1000)
  const y = dt.getFullYear()
  const m = (dt.getMonth() + 1 + '').padStart(2, '0') // 月份從0開始的,所以加1;不足2位的補0
  const d = (dt.getDate() + '').padStart(2, '0')
  const hh = (dt.getHours() + '').padStart(2, '0')
  const mm = (dt.getMinutes() + '').padStart(2, '0')
  const ss = (dt.getSeconds() + '').padStart(2, '0')
  return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
})

回到List.vue里添加代碼:

<el-table-column prop="add_time" label="創建時間" width="140px">
        <template slot-scope="scope">
            <!--通過作用域插槽的形式 調用時間過濾器-->
            {{scope.row.add_time | dateFormat}}
        </template>
</el-table-column>

刷新頁面,創建時間已經變成常見格式。

6、實現商品列表的分頁功能

添加分頁代碼:

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

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

size-change   pageSize改變時會觸發
current-change   currentPage改變時會觸發
current-page   當前頁數
page-sizes   每頁顯示個數選擇器的選項設置
page-size   每頁顯示條目個數
total   總條目數
設置 background 屬性可以為分頁按鈕添加背景色

效果圖:

7、實現搜索與清空的功能

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

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

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

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

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

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

效果圖:

8、根據id刪除商品數據

給刪除按鈕添加點擊事件:根據id

<!--刪除按鈕-->
<el-button type="danger" size="mini" icon="el-icon-delete" @click="removeById(scope.row.goods_id)"></el-button>

removeById函數:

調用api的刪除商品接口,請求路徑:goods/:id,請求方法:delete

// 根據ID刪除對應的商品信息
async removeById(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('已取消刪除')
      }
      // console.log('確認刪除')
      const { data: res } = await this.$http.delete('goods/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('刪除商品失敗!')
      }
      this.$message.success('刪除商品成功!')
      this.getGoodsList()
}

實現刪除功能后刷新列表。

9、渲染編輯修改商品的對話框

給編輯按鈕添加點擊事件:

<!--修改按鈕-->
<el-button type="primary" size="mini" icon="el-icon-edit"
 @click="showEditDialog(scope.row.goods_id)"></el-button>

showEditDialog函數:

// 監聽 展示編輯商品的對話框
showEditDialog(id) {
      this.editDialogVisible = true
}

添加編輯商品對話框:

<!--編輯參數的對話框-->
<el-dialog title="編輯商品" :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClosed">
    <!--內容主體區域-->
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="90px">
      <el-form-item label="商品名稱" prop="goods_name">
        <el-input v-model="editForm.goods_name"></el-input>
      </el-form-item>
      <el-form-item label="商品價格" prop="goods_price">
          <el-input v-model="editForm.goods_price"></el-input>
      </el-form-item>
      <el-form-item label="商品數量" prop="goods_number">
          <el-input v-model="editForm.goods_number"></el-input>
      </el-form-item>
      <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editForm.goods_weight"></el-input>
      </el-form-item>
      <el-form-item label="商品介紹" prop="goods_introduce">
          <el-input v-model="editForm.goods_introduce"></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="editGoods">確 定</el-button>
    </span>
</el-dialog>

<script>
export default {
  data() {
    return {
      editDialogVisible: false, // 控制編輯商品對話框是否顯示
      // 編輯商品的表單數據對象
      editForm: {
        goods_name: '',
        goods_price: null,
        goods_number: null,
        goods_weight: null,
        goods_introduce: '',
        goods_cat: []
},
// 編輯商品的驗證規則對象 editFormRules: { goods_name: [ { required: true, message: '請輸入商品名稱', trigger: 'blur' } ], goods_price: [ { required: true, message: '請輸入商品價格', trigger: 'blur' } ], goods_number: [ { required: true, message: '請輸入商品數量', trigger: 'blur' } ], goods_weight: [ { required: true, message: '請輸入商品重量', trigger: 'blur' } ] } } }, methods: { // 監聽 展示編輯商品的對話框 showEditDialog(id) { this.editDialogVisible = true const { data: res } = await this.$http.get('goods/' + id) if (res.meta.status !== 200) { return this.$message.error('查詢角色信息失敗') } this.editForm = res.data }, // 監聽 編輯商品對話框的關閉事件 editDialogClosed() { // 表單內容重置為空 this.$refs.editFormRef.resetFields() }, // 點擊確認 編輯修改商品 editGoods() { }, } }

此時,點擊修改按鈕已經可以彈出對話框了。里面是對應的商品信息。

添加確定按鈕綁定點擊事件,完成商品信息的修改:

調用api的1.8.4. 編輯提交商品 接口,請求路徑:goods/:id  請求方法:put

// 點擊確認 編輯修改商品
editGoods() {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 可以發起修改商品信息的網絡請求
        const { data: res } = await this.$http.put(
          'goods/' + this.editForm.goods_id,
          { goods_name: this.editForm.goods_name,
            goods_price: this.editForm.goods_price,
            goods_number: this.editForm.goods_number,
            goods_weight: this.editForm.goods_weight,
            goods_introduce: this.editForm.goods_introduce,
            goods_cat: this.editForm.goods_cat
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改商品信息失敗!')
        }
        this.$message.success('修改商品信息成功!')
        // 關閉對話框
        this.editDialogVisible = false
        // 重新發起請求商品列表
        this.getGoodsList()
      })
},

效果圖:

 

接下面添加商品功能 

備注:格式化時間的過濾器,應該再*1000,上面代碼已修改


免責聲明!

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



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