整理vue + element-ui常用的功能及代碼片段

目錄:
1 常用表頭搜索:input+select+daterange
2 表格中對【上下架】、【排序】、【選擇】進行編輯
3 使用vue-clipboard2實現復制鏈接的功能
4 使用vue-quill-editor實現富文本編輯
5 解決el-input類型為 type='number' 不顯示上下箭頭
6 解決當el-select選中值綁定為對象時處理
7 使用upload照片墻多圖上傳-自定義方式顯示(方便回顯編輯)
8 vue+element-ui+form 實現動態生成表單
9 vue+element-ui+table 實現動態表頭+可編輯表格
10 table表格組件自定義索引,多頁數據從1開始排序
11 餓了么自定義滾動條el-scrollbar組件
12餓了么圖片點擊放大預覽組件el-image-viewer

1.常用表頭搜索:input+select+daterange

<template>
  <!-- 搜索數據 -->
    <el-card style="margin:10px;">
      <el-form :inline="true" :model="dataForm" label-width='100px'>
        <el-form-item label="標題:">
          <el-input v-model="dataForm.title" placeholder="請輸入資訊標題關鍵字" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否上架:">
          <el-select v-model="dataForm.status" placeholder="請選擇上架狀態" clearable>
            <el-option label="已上架" value="1"></el-option>
            <el-option label="未上架" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="添加日期:">
          <el-date-picker v-model="dataForm.time" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
            start-placeholder="開始日期" end-placeholder="結束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item style="float:right;">
          <el-button type="primary" @click="getDataList()">搜索</el-button>
          <el-button @click="resetBtn()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
</template>
 export default {
  name: 'newsList',
  data() {
    return {
      dataForm: {}, //搜索數據
      tableData: [], //表格數據
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
    }
  },
  created() { // 實例被創建之后執行代碼
    this.getDataList()
  },
  methods: { // 方法
     //請求數據列表
    getDataList() {
      const params = {
        'currentPage': this.pageIndex,
        'pageSize': this.pageSize,
        'title': this.dataForm.title ? this.dataForm.title : null,
        'status': this.dataForm.status ? this.dataForm.status : null,
        'startTime': this.dataForm.time ? this.dataForm.time[0] + ' 00:00:00' : null,
        'endTime': this.dataForm.time ? this.dataForm.time[1] + ' 23:59:59': null
      }
      /***接口方法***/(params).then(res => {
        if (res.data.code == 0) {
          //成功方法
        } else {
          //失敗方法
        }
      })
    },
    //重置
    resetBtn() {
      this.dataForm = {}
      this.getDataList(this.pageIndex, this.pageSize)
    },
  },

element 表格搜索,如果頁碼出現大量變換,一般重置第一頁開始展示

btnSearch() {
  this.pageIndex = 1
  this.getDataList()
}

element 分頁,切換一頁顯示條數方法,如果頁碼出現大量變換,一般重置第一頁開始展示

btnSearch(val) {
  this.pageIndex = 1
  this.pageSize=val
  this.getDataList()
}

2.表格中對【上下架】、【排序】、【選擇】進行編輯

<!-- 列表 -->
    <el-card style="margin:10px;">
      <el-table :data="tableData" border v-loading="tableLoading" style="width: 100%;">
        <!-- switch  change事件上下架 -->
        <el-table-column prop="borrowTypeName" header-align="center" align="center" label="是否上架">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.status==1?'正常':'禁用'" placement="top">
                 <el-switch :active-value="scope.row.status=== 1" :inactive-value="scope.row.status=== 0" active-color="#13ce66" inactive-color="#ff4949" @change='switchChange(scope.row)'></el-switch>
                 <!-- <el-switch v-model='scope.row.status' :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" @change='switchChange(scope.row)'>
                 </el-switch> -->
                 <!-- 當接收參數為數字的時候可以兩種寫法互相試一下 -->
             </el-tooltip>
          </template>
        </el-table-column>
       <!-- button  click事件上下架 -->
        <el-table-column prop="borrowTypeName" header-align="center" align="center" label="是否上架">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.status==1?'是':'否'" placement="top">
              <el-button type="danger" v-if="scope.row.status==1" plain size="small"
                @click="buttonChange(scope.$index,scope.row)">去下架</el-button>
              <el-button type="success" v-if="scope.row.status==2" plain size="small"
                @click="buttonChange(scope.$index,scope.row)">去上架</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- input  Enter事件排序 -->
        <el-table-column prop="ord" header-align="center" align="center" label="排序(Enter鍵確定)">
          <template slot-scope="scope">
            <el-button plain  size="medium" v-if="isChangeOrd" @click="isChangeOrd=false">{{scope.row.ord}}</el-button>
            <el-input v-model="scope.row.ord" suffix-icon='el-icon-edit' v-else placeholder="無" @keyup.enter.native="changeOrd(scope.$index,scope.row)"></el-input>
          </template>
        </el-table-column>
      <!-- select  change事件 -->
       <el-table-column header-align="center" align="center" label="個性化推薦">
        <template slot-scope="scope">
          <el-select  @change="changeOption($event,scope.row)"  v-model="scope.row.recommendIndex">
              <el-option :value="0" label="默認"></el-option>
              <el-option :value="1" label="推薦到首頁"></el-option>
              <el-option :value="2" label="推薦到熱門"></el-option>
            </el-select>
        </template>
      </el-table-column>

     </el-table>
    </el-card>
export default {
  name: 'newsList',
  data() {
    return {
      isChangeOrd: true, //更改排序
    }
  },
  methods: { // 方法
   //switch是否上架
    switchChange(row) { 
        const params = {};
        params.id = row.id;
        params.status = row.status == 1 ? 0 : 1;
        /***接口方法***/(params).then(res => {
          if (res.code == 0) {
            this.getDataList()
            this.$message.success(res.data.msg);
          }
        })
      },
     //button是否上架
    buttonChange(index, row) {
      let params = {
        id: row.id,
        status: row.status == 1 ? '2' : '1'
      }
      ***接口方法***(params).then(res => {
        if (res.data.code == 0) {
          this.getDataList()
          this.$message.success(res.data.msg);
        }
      })
    },
    //更改排序
    changeOrd(index, row) {
      let params = {
        id: row.id,
        ord: row.ord
      }
      /***接口方法***/(params).then(res => {
        if (res.data.code == 0) {
          this.getDataList()
          this.isChangeOrd = true;
          this.$message.success(res.data.msg);
        }
      })
    },
    //個性化推薦
    changeOption (e, row) {
        let params = {
          proId: row.proId,
          recommendIndex: e
        }
       ***接口方法***(params).then(res => {
        if (res.data.code == 0) {
          this.getDataList()
          this.$message.success(res.data.msg);
        }
      })
     }
  },

3.使用vue-clipboard2實現復制鏈接的功能

1.安裝vue-clipboard2插件

npm install --save vue-clipboard2

2.在main.js里引入:

import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)

3.在.vue頁面中使用

<el-button  type="success"  v-clipboard:copy="(scope.row.link)" v-clipboard:success="onCopy" 
v-clipboard:error="onError">復制鏈接</el-button>

4.在methods中寫入方法

methods: { // 方法
   // 復制成功
     onCopy (e) {
       this.$message.success(`復制成功  ${e.text}`)
     },
     // 復制失敗
     onError (e) {
       this.$message.error(`復制失敗`)
     },
}

4.使用vue-quill-editor實現富文本編輯

1.安裝依賴

npm install vue-quill-editor –save

2.在main.js里引入:

import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

Vue.use(VueQuillEditor)

3.在.vue頁面中使用

<div>
  <quill-editor v-model="ruleForm.content" ref="myQuillEditor" class="editer" 
@blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
 @ready="onEditorReady($event)" @change="onEditorChange($event)"></quill-editor>
</div>

4.在methods中寫入方法

methods: { // 方法
   onEditorBlur(){}, // 失去焦點事件
   onEditorFocus(){}, // 獲得焦點事件
   onEditorChange(){}, // 內容改變事件
   onEditorReady(){}
}

5.解決el-input類型為 type='number' 不顯示上下箭頭

改變之前

改變之后

1.html代碼:

<el-input v-model="form.newMemberBonus" type='number'></el-input>

2.css代碼:

<style  lang='scss'>

    // 處理input type = number的上下箭頭
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }

    input[type="number"] {
      -moz-appearance: textfield;
    }

</style>

6.解決當el-select選中值綁定為對象時處理

<el-form-item label="字段:">
   <el-select v-model="ruleForm.detail" multiple placeholder="請選擇" value-key="id" @change="chooseField($event)">
     <el-option v-for="(item) in DataField" :key="item.id" :label="item.columnComment" :value="item">
     </el-option>
   </el-select>
</el-form-item>

要點:value綁定的是對象時,在el-select 添加value-key="id"屬性,el-option中添加:key="item.id"屬性。其中value-key的值與key綁定的屬性值對應。

7.使用upload照片墻多圖上傳-自定義方式顯示(方便回顯編輯)

自定義顯示圖片數組
<template>
    <div style="display:inline-block;">
      <el-upload action="/admin/adminOss/imgUpload" list-type="picture-card" :show-file-list="false"
                :headers="headers" :on-success="multipleUploadSuccess" :on-remove="handleRemove" :limit='5'>
          <i class="el-icon-plus"></i>
      </el-upload>
    </div>
    <div class="color-item" v-for="(item,index) in multipleList" @dblclick='dblclick(index)' :key="index">
          <img :src="item" alt="" srcset="">
     </div>
     <div class="tips">商品詳情圖:(最多可以上傳5張圖片,建議尺寸800*800px,雙擊可刪除)</div>
</template>
import store from '@/store'
export default {
  name: 'newsList',
  data() {
    return {
     headers: { //上傳圖片headers
        Authorization: 'Bearer ' + store.getters.access_token
      },
      multipleList: [], //詳情圖圖片數組
    }
  },
  methods: { // 方法
    //圖片上傳成功回調,將圖片放入顯示的數組中
    multipleUploadSuccess(res, file) {
      this.multipleList.push(res.data)
    },
    //原自帶刪除改寫為下面的雙擊刪除
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //雙擊刪除多圖
    dblclick(e) { //雙擊刪除
      this.multipleList.splice(e, 1)
    }
  }
<style scoped lang='scss'>
    .tips {
      font-size: 14px;
      margin-bottom: 20px;
    }

    /* 多張 */
    .color-item {
      display: inline-block;
      float: left;
      border: 1px dashed #ddd;
      margin: 5px 5px 0 0;
      padding: 1px;

      img {
        width: 130px;
        height: 130px;
      }
    }
</style>

8.vue+element-ui+form 實現動態生成表單

初始狀態

點擊添加之后

可切換活動類型

elementUI官網有對單表單的添加,實現方式是,先寫死一個必須的表單,需要新增表單的放在一個div里,在div中使用v-for生成,達到同時增加的效果
以下為代碼(請靈活運用):

  <template>
     <div class="title">活動規則:</div>
      <el-form status-icon label-width="68px" class="demo-ruleForm">
        <el-form-item label="活動類型">
          <el-radio-group v-model="ruleForm.type" @change='radioChoose'>
            <el-radio :label="1">滿減促銷</el-radio>
            <el-radio :label="2">滿折促銷</el-radio>
          </el-radio-group>
        </el-form-item>
          <div v-for="(item, index) in reduceList" :key="index">
            <el-row>
              <el-col :span="3">
                <el-form-item label="滿">
                  <el-input v-model="item.fullPrice"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3" v-if="ruleForm.type==1">
                <el-form-item label="減">
                  <el-input v-model="item.reducePrice"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3" v-else>
                <el-form-item label="折">
                  <el-input v-model="item.discount"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="1">
                <el-button type="success" icon="el-icon-plus" plain
                  @click.prevent="addConfigList"></el-button>
                <el-button v-if="reduceList.length>1" type="danger" icon="el-icon-minus" plain
                  @click.prevent="removeConfigList(item)"></el-button>
              </el-col>
            </el-row>
          </div>
      </el-form>
  </template>
export default {
  name: 'addActivity',
  data() {
    return {
     ruleForm: {
        type: '', //促銷類型
      },
      reduceList: [{ //滿減滿折促銷規則----先寫死一個即初始狀態圖
        type: '',   //1:滿減促銷  2:滿折促銷
        fullPrice: '',
        reducePrice: '',
        discount: ''
      }],
    }
  },
  methods: { // 方法
    //新增一條規則配置
    addConfigList() {
      if (this.ruleForm.type == 1) {  //此處就是判斷不同活動類型 定義不同的type
        this.reduceList.push({
          type: 1,  //1:滿減促銷  2:滿折促銷
          fullPrice: '',
          reducePrice: '',
          discount: ''
        })
      } else {
        this.reduceList.push({
          type: 2,  //1:滿減促銷  2:滿折促銷
          fullPrice: '',
          reducePrice: '',
          discount: ''
        })
      }
  },
   //刪除一條規則配置
    removeConfigList(item) {
      if (item.id) { //有id接口刪除  無本地刪除( 自行和后臺約定)
        let params = {
          id: item.id
        }
        /*******接口方法******/(params).then(res => {
          if (res.data.code == 0) {
            this.$message.success(res.data.msg);
            let index = this.reduceList.indexOf(item)
            if (index !== -1) {
              this.reduceList.splice(index, 1)
            }
          }
        })
      } else {   //本地刪除
        let index = this.reduceList.indexOf(item)
        if (index !== -1) {
          this.reduceList.splice(index, 1)
        }
      }
    },

注意:刪除行的話 本地刪除或者接口刪除要根據后臺定義,要是本地刪除就更簡單了。參考文章

9.vue+element-ui+table 實現動態表頭+可編輯表格

項目要求:
1.根據選擇不同屬性類型顯示不同的表頭,表頭中銷售價格、市場價格、屬性圖是固定的
2同時屬性類型及屬性類型的值都是動態的
3同時可以動態添加或刪除一條數據

表頭一
表頭二

以下為代碼(固定表頭的圖片字段部分去掉了,不是此次要點):

    <el-table :data="skuData" class="tb-edit" style="width: 80%" border align="center">
            <!-- 動態表頭 -->
            <el-table-column v-for="(item,index) in attributeList" :label="item.name"  :key="index"
               :property="item.name" align="center" >
              <template slot-scope="scope">
                <el-select v-model="scope.row[scope.column.property]" clearable placeholder="請選擇" value-key="id"  
                  @change="selectNumber($event)">
                  <el-option v-for="attItem  in item.sysCommodityAttributeValueEntities" :key="attItem.id" 
                    :label="attItem.value" :value="attItem">
                  </el-option>
                </el-select>  
              </template>
            </el-table-column>
            <!-- 固定表頭 -->
            <el-table-column header-align="center" align="center" label="銷售價格">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" suffix-icon='el-icon-edit' placeholder="銷售價格"></el-input>
              </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" label="市場價格">
              <template slot-scope="scope">
                <el-input v-model="scope.row.marketPrice" suffix-icon='el-icon-edit' placeholder="市場價格"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template slot-scope="scope">
                <el-button size="mini" plain type="success" @click="handleSkuSave(scope.$index,scope.row)">查驗
                </el-button>
                <el-button size="mini" plain type="danger" @click="handleSkuDelete(scope.$index,scope.row)">刪除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
export default {
  name: 'addProduct',
  data() {
    return {
      //動態表頭--屆時是后臺返回的,為了方便觀看所以寫死的
       attributeList:[{
              name:'容量',
              property:'capacity',
              sysCommodityAttributeValueEntities:[{id:1,value:'48v'},{id:2,value:'60v'},{id:3,value:'72v'}]
          },{
              name:'顏色',
              property:'color',
              sysCommodityAttributeValueEntities:[{id:1,value:'紅色'},{id:2,value:'黑色'}]
         }]
      //表格數據
        skuData: [{  //默認寫死一條固定表頭的字段
              price: '',   //銷售價格
              marketPrice: '',  //市場價格
            }], 
         }
  },
  methods: { // 方法
     //添加一條貨品sku
    handleAddOneSku() {
      let oneSkuData = {
        price: '',
        marketPrice: '',
      }
      this.skuData.push(oneSkuData)
    },
    //sku表單行刪除
    handleSkuDelete(index, row) {
       this.skuData.splice(index, 1)
    },
  }

動態渲染表頭核心代碼(通過一個循環拿到列的標簽和列名):

<!-- 動態表頭 -->
  <el-table-column v-for="(item,index) in attributeList" :label="item.name" :property="item.name" align="center" :key="index">
      <template slot-scope="scope">
      <el-select v-model="scope.row[scope.column.property]" clearable placeholder="請選擇" value-key="id"  
                  @change="selectNumber($event)">
        <el-option v-for="attItem  in item.sysCommodityAttributeValueEntities" :key="attItem.id" 
                    :label="attItem.value" :value="attItem">
        </el-option>
      </el-select>  
    </template>
  </el-table-column>

要點:在自定義模板里面通過scope.row[scope.column.property]取到當前行的列字段與下拉框進行雙向綁定,這樣就是實現了可編輯的動態表頭的表格。參考文章

10.table組件自定義索引,多頁數據從1開始排序

定義type=index表示索引列
自定義索引方法 :index="indexMethod"

<template>
  <el-table
    :data="tableData"
    style="width: 100%">
    <el-table-column
      type="index"
      :index="indexMethod">
    </el-table-column>
  </el-table>
</template>
methods: {
    indexMethod(index) {
      return (this.pageNum-1) * this.pageSize +index +1
}

tips:
this.pageNum:表示當前頁碼數
this.pageSize:表示每頁顯示的條數
index:table中:表示數據的索引,從0開始
(this.pageNum-1) * this.pageSize +index +1 :表示當前頁的索引開始值
例如:每頁顯示10條數據,第三頁起始值則為21開始。(3-1)* 10 + 0 + 1 = 21

11 餓了么自定義滾動條el-scrollbar組件
image.png

滾動條組件

<el-scrollbar></el-scrollbar>

(1)已知內容高度

<div style='height:800px'>
    <el-scrollbar class='page-component__scroll'></el-scrollbar>
<div>
<style>
    .page-component__scroll{
        height: 100%;
    }
    .page-component__scroll .el-scrollbar__wrap {
        overflow-x: auto;
    }
<style>

(2)高度由內容撐開

<html>
    <body>
        <div style='height:100%'>
            <el-scrollbar class='page-component__scroll'></el-scrollbar>
        <div>
    </body>
</html>
<style>
  html,body{
      height:100%
      overflow:hidden; /*有效防止在頁面進行手動刷新時顯示內置滾動條*/
  }
  .page-component__scroll{
      height: 100%;
  }
  .page-component__scroll .el-scrollbar__wrap {
      overflow-x: auto;
  }
<style>
12、圖片預覽組件el-image-viewer
<template>
    //...
     <!-- 查看圖片 -->
    <el-image-viewer v-if="showViewer" :on-close="() => {showViewer = false;}" :url-list="imgList" />
</template>
<script>
  data(){
    return{
        showViewer:false,
        imgList:['','','',],  //放大展示圖片一維數組
  }
},
components: {
    "el-image-viewer": () =>import("element-ui/packages/image/src/image-viewer"),
},
</script>

【后續會繼續添加】

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • (o゜▽゜)o☆ 青椒味的Hello World 沒有項目工程,沒有vue腳手架,就一個HTML頁面;沒有干貨,純...
    dobby_l閱讀 13,146評論 0 6
  • 基于Vue的一些資料 內容 UI組件 開發框架 實用庫 服務端 輔助工具 應用實例 Demo示例 element★...
    嘗了又嘗閱讀 1,175評論 0 1
  • 本文為2016年11月9日,『前端之巔』微信群在線分享活動總結整理而成,轉載請在文章開頭處注明來自『前端之巔』公眾...
    尾尾閱讀 10,670評論 3 32
  • UI組件 element- 餓了么出品的Vue2的web UI工具套件 Vux- 基于Vue和WeUI的組件庫 m...
    小姜先森o0O閱讀 9,612評論 0 72
  • 一個人睡,一個人吃飯,一個人逛街,一個人看電視…… 是的,一個人。獨來獨往,我的思想主宰我的行動,...
    郁婕閱讀 178評論 0 1