Vue element商品列表的增刪改功能實現

介紹 

整體和用戶列表 類似 功能步驟有:

  • 面包屑導航
  • 外部是大的卡片組件
  • 搜索商品 添加商品
  • 表格渲染數據
  • 作用域插槽用於 操作按鈕
  • 分頁器組件的使用

不一樣的點:之前編輯信息 新增信息是 彈出對話框編輯 但商品信息內容較多 我們跳轉到一個組件、並且進行商品編輯的時候要進行路由傳參 來渲染初始數據

點擊添加商品按鈕時跳轉到新增商品組件對應路徑:

addGoods(){
this.$router.push('/goods/add')
}

點擊編輯商品按鈕時跳轉到編輯商品組件對應路徑 並且傳入id

ToEditGoods(id){
this.$router.push(`/goods/edit/${id}`) 
}

新增商品和編輯商品組件佈局一致隻是新增商品 不用 傳參請求數據

我們以編輯商品為例

在設置路由對應關系的時候 預留占位符

{
  path:'/goods',
  component:GoodsList
},
{
  path:'/goods/add',
  component:GoodsAdd
},
{
  path:'/goods/edit/:id',
  component:GoodsEdit
}

第一步 先使用組件進行頁面佈局:

主要使用到瞭 el-steps 步驟條組件 和 el-tabs 標簽頁組件的聯動 使他們步長一致 使用共同的

active 步驟條的active 動態綁定 到 activeIndex上

當標簽頁發生切換時 根據name 賦值給 activeIndex

 

async handleClick(){
   this.activeIndex = this.activeName * 1
   // 選擇瞭商品(動態)參數選項
 },

 

這樣 兩個組件就可以聯動展示瞭

標簽頁組件其實是包裹在 el-form 當中方便統一提交給服務器

接下來就是表單內部 組件渲染 表單驗證瞭

基本信息

組件渲染el-input 數據綁定 v-model 類型限制 tpye=‘number’ prop合法值驗證

這裡需要自定義驗證的是 商品價格不能小於0 商品數量必須是整數

必填就可以直接使用自帶的

基本信息中還有一個要點:分類選擇

          <el-form-item label="選擇商品分類">
el-cascader 級聯選擇器
            <el-cascader
默認選定的值是根據id請求過來的分類數組
              v-model="AddGoodsForm.goods_cat"
              style="width: 400px"
數據來源:cateLists 一進入頁面請求過來的
              :options="cateLists"
有清空按鈕
              clearable
禁用 編輯頁面 不讓修改分類
              disabled
級聯選擇器的相關規則
              :props="CSet"
選擇發生改變時 執行的回調
              @change="handleChange"></el-cascader>
          </el-form-item>
<script>
數據來源:
      async getAllCate(){
        const {data:res} = await this.$http.get('categories')
        if (res.meta.status !==200) return this.$Msg.error('獲取商品分類列表失敗!')
        this.cateLists = res.data
      }
級聯選擇器的規則
        CSet:{
展示下一級觸發方式 鼠標懸浮
          expandTrigger: 'hover',
指定選項的子選項為選項對象的某個屬性值
          children:'children',
顯示的文本
          label:'cat_name',
文本對應的value
          value:'cat_id',
        }
選擇發生改變時 執行的回調  隻讓選擇第三級  不是的話就清空 選擇不進去
      handleChange(){
        if (this.AddGoodsForm.goods_cat.length !== 3){
          this.AddGoodsForm.goods_cat = []
        }
        console.log(this.AddGoodsForm.goods_cat)
      }
<script>

如果是新增商品頁面的話 也大體一致 把 disabled 去掉即可

並且在切換標簽頁時可以驗證AddGoodsForm.goods_cat 的長度

      leaveTabs(activeName, oldActiveName){
        if(oldActiveName === '0' && this.AddGoodsForm.goods_cat.length !== 3){
          this.$Msg.error('請先選擇商品分類!')
          return false
        }

根據服務器返回的數據

渲染商品參數-attr.many 和商品屬性-attr.only

分別渲染 多選框組和輸入框組來v-for 循環

上傳主圖

        <el-tab-pane label="4.商品圖片" name="3">
          <el-upload
            class="upload-demo"
            :action="actionToUrl"
            :on-preview="handlePreview2"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :headers="UploadHeaders"
            list-type="picture-card">
            <el-button size="small" type="primary">點擊上傳</el-button>
            <div slot="tip" class="el-upload__tip">隻能上傳jpg/png文件,且不超過500kb</div>
          </el-upload>
        </el-tab-pane>
    <el-dialog
      title="預覽圖片"
      :visible.sync="Preview"
      width="45%">
      <img :src="PreviewPic" alt="" style="width: 100%">
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="Preview = false">確 定</el-button>
  </span>
    </el-dialog>
<script>
action	必選參數,上傳的地址 這裡用的是本地服務器
actionToUrl:'http://127.0.0.1:8888/api/private/v1/upload'
on-preview 點擊文件列表中已上傳的文件時的鉤子 點擊出現對話框顯示放大預覽圖
      handlePreview2(file){
        this.PreviewPic=file.response.data.url // 顯示圖片的地址
        this.Preview = true // 決定對話框顯示的佈爾值
      }
on-remove 文件列表移除文件時的鉤子
      handleRemove(file){
      //1.獲取將要刪除的圖片臨時路徑
        const fileUrl = file.response.data.tmp_path
      //2.從pics 數組中,找到這個圖片對應的索引值
        let aaa = this.AddGoodsForm.pics.findIndex(value => value === fileUrl)
        console.log(aaa)
      //3.調用數組 splice 方法 把圖片信息對象從pics 數組中移除
        this.AddGoodsForm.pics.splice(aaa,1)
        console.log(this.AddGoodsForm.pics)
      }
on-success 文件上傳成功時的鉤子
      async handleSuccess(response){
       // 找出定義一下 新上傳文件的路徑地址
       const NewPicUrl = response.data.tmp_path
       // push 到預留表單位中
        this.AddGoodsForm.pics.push(NewPicUrl)
        console.log(this.AddGoodsForm.pics)
        // const {data:res} = await this.$http.put(`goods/${this.NowEditId}/pics`,this.AddGoodsForm.pics)
        // if (res.meta.status !==200) return this.$Msg.error('更新主圖失敗!')
        // this.$Msg.success('更新主圖成功!')
      }
headers 設置上傳的請求頭部
        UploadHeaders:{
          Authorization:window.sessionStorage.getItem('token')
        },
</script>

商品信息vue富文本編輯器的配置

先執行安裝語句:

在main.js 中註冊 並引入樣式

npm install vue-quill-editor
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css' // import styles
import 'quill/dist/quill.snow.css' // for snow theme
import 'quill/dist/quill.bubble.css' // for bubble theme
Vue.use(VueQuillEditor, /* { default global options } */)

在組件中使用

        <el-tab-pane label="5.商品內容" name="4">
          <quill-editor
            ref="myQuillEditor"
數據雙向綁定 便於發送請求
            v-model="AddGoodsForm.goods_introduce"
富文本編輯器的核心配置
            :options="editorOption"
          />
        </el-tab-pane>
<script>
// 此處定義在data外
  const toolbarOptions = [
    ['insertMetric'],
    ['bold', 'italic', 'underline', 'strike'],        // 加粗,斜體,下劃線,刪除線
    ['blockquote', 'code-block'],                     //引用,代碼塊
    [{ 'header': 1 }, { 'header': 2 }],               // 幾級標題
    [{ 'list': 'ordered' }, { 'list': 'bullet' }],    // 有序列表,無序列表
    [{ 'script': 'sub' }, { 'script': 'super' }],     // 下角標,上角標
    [{ 'indent': '-1' }, { 'indent': '+1' }],         // 縮進
    [{ 'direction': 'rtl' }],                         // 文字輸入方向
    [{ 'size': ['small', false, 'large', 'huge'] }],  // 字體大小
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],        // 標題
    [{ 'color': [] }, { 'background': [] }],          // 顏色選擇
    [{ 'font': ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }], // 字體
    [{ 'align': [] }],    // 居中
    ['clean'],            // 清除樣式,
    ['link', 'image']   // 上傳圖片、上傳視頻
  ]
  // toolbar標題
  const titleConfig = [
    { Choice: '.ql-insertMetric', title: '跳轉配置' },
    { Choice: '.ql-bold', title: '加粗' },
    { Choice: '.ql-italic', title: '斜體' },
    { Choice: '.ql-underline', title: '下劃線' },
    { Choice: '.ql-header', title: '段落格式' },
    { Choice: '.ql-strike', title: '刪除線' },
    { Choice: '.ql-blockquote', title: '塊引用' },
    { Choice: '.ql-code', title: '插入代碼' },
    { Choice: '.ql-code-block', title: '插入代碼段' },
    { Choice: '.ql-font', title: '字體' },
    { Choice: '.ql-size', title: '字體大小' },
    { Choice: '.ql-list[value="ordered"]', title: '編號列表' },
    { Choice: '.ql-list[value="bullet"]', title: '項目列表' },
    { Choice: '.ql-direction', title: '文本方向' },
    { Choice: '.ql-header[value="1"]', title: 'h1' },
    { Choice: '.ql-header[value="2"]', title: 'h2' },
    { Choice: '.ql-align', title: '對齊方式' },
    { Choice: '.ql-color', title: '字體顏色' },
    { Choice: '.ql-background', title: '背景顏色' },
    { Choice: '.ql-image', title: '圖像' },
    { Choice: '.ql-video', title: '視頻' },
    { Choice: '.ql-link', title: '添加鏈接' },
    { Choice: '.ql-formula', title: '插入公式' },
    { Choice: '.ql-clean', title: '清除字體格式' },
    { Choice: '.ql-script[value="sub"]', title: '下標' },
    { Choice: '.ql-script[value="super"]', title: '上標' },
    { Choice: '.ql-indent[value="-1"]', title: '向左縮進' },
    { Choice: '.ql-indent[value="+1"]', title: '向右縮進' },
    { Choice: '.ql-header .ql-picker-label', title: '標題大小' },
    { Choice: '.ql-header .ql-picker-item[data-value="1"]', title: '標題一' },
    { Choice: '.ql-header .ql-picker-item[data-value="2"]', title: '標題二' },
    { Choice: '.ql-header .ql-picker-item[data-value="3"]', title: '標題三' },
    { Choice: '.ql-header .ql-picker-item[data-value="4"]', title: '標題四' },
    { Choice: '.ql-header .ql-picker-item[data-value="5"]', title: '標題五' },
    { Choice: '.ql-header .ql-picker-item[data-value="6"]', title: '標題六' },
    { Choice: '.ql-header .ql-picker-item:last-child', title: '標準' },
    { Choice: '.ql-size .ql-picker-item[data-value="small"]', title: '小號' },
    { Choice: '.ql-size .ql-picker-item[data-value="large"]', title: '大號' },
    { Choice: '.ql-size .ql-picker-item[data-value="huge"]', title: '超大號' },
    { Choice: '.ql-size .ql-picker-item:nth-child(2)', title: '標準' },
    { Choice: '.ql-align .ql-picker-item:first-child', title: '居左對齊' },
    { Choice: '.ql-align .ql-picker-item[data-value="center"]', title: '居中對齊' },
    { Choice: '.ql-align .ql-picker-item[data-value="right"]', title: '居右對齊' },
    { Choice: '.ql-align .ql-picker-item[data-value="justify"]', title: '兩端對齊' }
  ]
// 此處書寫在data當中
        editorOption: {
          placeholder: '請在這裡輸入......',
          theme: 'snow', //主題 snow/bubble
          modules: {
            history: {
              delay: 1000,
              maxStack: 50,
              userOnly: false
            },
            toolbar: {
              container: toolbarOptions,
              handlers: {
                insertMetric: this.showHandle
              }
            }
          }
        }
// 此處書寫在 methods 中
 // 配置富文本編輯器
      initTitle () {
        document.getElementsByClassName('ql-editor')[0].dataset.placeholder = ''
        for (let item of titleConfig) {
          let tip = document.querySelector('.quill-editor ' + item.Choice)
          if (!tip) continue
          tip.setAttribute('title', item.title)
        }
      },
      showHandle () {
        this.$Msg.error('這是自定義工具欄的方法!')
      },
      // 自定義按鈕內容初始化
      initButton () {
        const editorButton = document.querySelector('.ql-insertMetric')
        editorButton.innerHTML = '<i class="el-icon-link" style="font-size: 18px;color:black"></i>'
      },
      // 失去焦點
      onEditorBlur (editor) { },
      // 獲得焦點
      onEditorFocus (editor) { },
      // 開始
      onEditorReady (editor) { },
      // 值發生變化
      onEditorChange (editor) {
        // 如果需要手動控制數據同步,父組件需要顯式地處理changed事件
        // this.content = editor.html;
        console.log(editor);
      },
</script>

最後提交數據

        <el-tab-pane label="6.提交商品" name="5">
          <el-empty image="http://www.wsg3096.com/gangback/pub/asdc1.png" :image-size="320" description="確定所有數據添加完畢後就可以提交啦!">
            <el-button type="primary" icon="el-icon-success" @click="ToGoods">上傳商品</el-button>
          </el-empty>
        </el-tab-pane>
<script>
      // 確定上傳的按鈕
      async ToGoods(){
        this.$refs.AddGoodsFormRef.validate(async valid =>{
          if (!valid)  return this.$Msg.error('請檢查下各項數據是否規范!')
          // 執行添加業務的邏輯 先深拷貝一下 防止改變 級聯選擇器
          const form = _.cloneDeep(this.AddGoodsForm)
          // 處理當前商品所屬ID 服務器要求 ,分割的字符串
          form.goods_cat = form.goods_cat.join(',')
          // 請求過來的數據保存到ManyData OnlyData 展示 返回去的時候 還用服務器的數據就行
          form.attrs = [...this.ManyData,...this.OnlyData]
         // console.log(form)
          const {data : res} = await this.$http.put(`goods/${this.NowEditId}`,form)
          if (res.meta.status !== 200) return this.$Msg.error('編輯商品失敗!')
          this.$Msg.success('編輯商品成功!')
          await this.$router.push('/goods')
        })
      }
</script>

到此這篇關於Vue element商品列表的增刪改功能實現的文章就介紹到這瞭,更多相關Vue element商品列表內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: