1. 程式人生 > 程式設計 >Vue使用Element實現增刪改查+打包的步驟

Vue使用Element實現增刪改查+打包的步驟

在我們進行專案開發期間,避免不了使用各式各樣的元件,Element是由餓了麼公司前端團隊開源。樣式精美、元件齊全、易於上手。

效果:

Vue使用Element實現增刪改查+打包的步驟

元件使用

我們利用vue-cli建立一個專案,然後只需要安裝element-ui即可

安裝:npm i element-ui -S

然後在main.js中引用一下樣式即可,可以選擇按需載入,我們這邊因為是演示一下,所以不去進行調整,專案中如果使用到的元件不多,可以選擇按需載入。

main.js

import Vue from 'vue';
import App from './App.vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false;

Vue.use(ElementUI);

new Vue({
 render: h => h(App),}).$mount('#app')

然後我們在src/components下新建一個元件,用來寫我們的展示元件,然後在app.vue中匯入即可

app.vue

<template>
 <div id="app">
  <Creator content1="憧憬"/>
 </div>
</template>

<script>
import Creator from './components/Creator/Creator';

export default {
 name: 'app',components: {
  Creator
 }
}
</script>

我們首先先使用表格,將資料展示出來

Creator.vue

<template>
  <div class="Creator">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input v-model="content" placeholder="請輸入內容"></el-input>
      </el-col>

      <el-col :span="2">
        <el-button type="primary">搜尋</el-button>
      </el-col>
    </el-row>

    <div style="height: 20px"/>

    <el-row :gutter="10" type="flex" justify="center">
      <el-col :span="14">
        <el-table
            :data="tableData"    // 宣告列表使用的資料
            :key="'zip'"      // 宣告每一行的key
            border
            style="width: 100%">
          <el-table-column
              fixed
              prop="date"
              label="日期"
              width="150">
          </el-table-column>
          <el-table-column
              prop="name"     // 對應tableData裡面的需要展示的鍵
              label="姓名"
              width="120">
          </el-table-column>
          <el-table-column
              prop="province"
              label="省份"
              width="120">
          </el-table-column>
          <el-table-column
              prop="city"
              label="市區"
              width="120">
          </el-table-column>
          <el-table-column
              prop="address"
              label="地址"
              width="300">
          </el-table-column>
          <el-table-column
              prop="zip"
              label="郵編"
              width="120">
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="160"
              v-slot="scope" // 獲取每一行的資料
           >
            <template>    
              <el-button @click="handleCreate(scope.row)"   type="text" size="small">新增</el-button>
              <el-popconfirm
                  confirmButtonText='好的'
                  cancelButtonText='不用了'
                  icon="el-icon-info"
                  iconColor="red"
                  title="這是一段內容確定刪除嗎?"
                  @onConfirm="handleDelete(scope.row)"
              >
                <el-button slot="reference" type="text" size="small">刪除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>


    <el-dialog title="新增使用者" :visible.sync="dialogFormVisible">
    // rules指定表單驗證規則
      <el-form :model="form" status-icon ref="ruleForm" :rules="rules" :label-position="'right'">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item prop="name" label="姓名" :label-width="formLabelWidth">
              <el-input style="width: 200px" v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item
                prop="dates"  // 需要驗證的欄位 需要對應rules裡面的鍵
                label="日期"
                :label-width="formLabelWidth"
                :rules="[
                  {required: true,message: '必須選擇一個日期',trigger: 'blur'},]"     // 也可以直接寫在item裡面驗證 也可以全放在rules。我這裡是採取了兩種方式
            >
              <el-date-picker
                  v-model="form.dates"
                  align="right"
                  type="date"
                  placeholder="選擇日期"
                  format="yyyy 年 MM 月 dd 日" // 展示資料的格式
                  value-format="yyyy-MM-dd"    // 宣告點選後的資料格式
                  :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onOk">確 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    props: {
      content1: {required: true,type: String}
    },data() {
    
      // 自定義驗證函式 給name驗證
      const validatName = (rule,value,callback) => {
        if (!value) return callback(new Error('名字不能為空'));
        if (value.length <= 0) return callback(new Error('最少一個字元'));
        return callback();
      };

      return {
        content: this.content1,tableData: [
          {
            date: '2016-05-02',name: '王小虎',province: '上海',city: '普陀區',address: '上海市普陀區金沙江路 1518 弄',zip: 200331
          },{
            date: '2016-05-04',address: '上海市普陀區金沙江路 1517 弄',zip: 200332
          },{
            date: '2016-05-01',address: '上海市普陀區金沙江路 1519 弄',zip: 200333
          },{
            date: '2016-05-03',address: '上海市普陀區金沙江路 1516 弄',zip: 200334
          }],formLabelWidth: '120px',// 控制模態是否展示
        dialogFormVisible: false,form: {
          name: '',dates: null,},// 對picker元件的擴充套件
        pickerOptions: {
          // 將之後的時間禁用 不然選擇
          disabledDate(time) {
            return time.getTime() > Date.now();
          },// 增加 今天 昨天 一週前的快速選項
          shortcuts: [{
            text: '今天',onClick(picker) {
              picker.$emit('pick',new Date());
            }
          },{
            text: '昨天',onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick',date);
            }
          },{
            text: '一週前',onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick',date);
            }
          }]
        },// 定義輸入規則
        rules: {
          name: [
              // 指定驗證函式       觸發時機。這個是失去焦點觸發
            {validator: validatName,trigger: 'blur'}
          ],};
    },methods: {
      onOk() {
        
        // 使用ref進行驗證 validate傳入一個函式 返回一個驗證是否成功的bool值
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {

            const {
              name,dates
            } = this.form;

          // 避免zip重複 zip++
            const maxZip = Math.max(...this.tableData.map(item => item.zip)) + 1;

            const obj = {
              name,date: dates,province: '北京',zip: maxZip
            };

        // push到資料裡面
            this.tableData.push(obj);

        // 將模態隱藏
            this.dialogFormVisible = false;
          } else {
            return false;
          }
        });
      },// 刪除資料
      handleDelete(row) {
        this.tableData.map((item,index) => {
          if (item.zip === row.zip) {
            this.tableData.splice(index,1);
          }
        });
      },handleCreate() {
        // 模態展示
        this.dialogFormVisible = true;
      }
    }
  };
</script>

一套基本的增刪改查就可以了呀,Vue有一套admin模版,開箱即用。
vue-element-admin非常不錯,大家可以去使用一下子

打包

預設打包的話會導致靜態資源引用存在問題,開啟一片空白,所以我們打包前需要先配置一下靜態資源
package.json這個檔案同級的目錄,新建一個vue.config.js,加入如下配置

/**
 * Created By 憧憬
 */
module.exports = {
  publicPath: './'    // 靜態資源目錄配置為./ 當前目錄
};

以上就是Vue使用Element實現增刪改查+打包的步驟的詳細內容,更多關於vue 增刪改查+打包的資料請關注我們其它相關文章!