spring boot + vue + element-ui全棧開發入門——前端編輯數據對話框

 需求css


 

1.點擊「添加」按鈕,彈出錄入數據的對話框窗口,並錄入數據,若是數據有誤則不容許提交。數據填寫完畢後,點擊「保存」按鈕,調用http協議提交數據,提交完畢刷新頁面數據。點擊「取消」按鈕關閉對話框。html

2.點擊列表中的「修改」按鈕,彈出數據修改對話框窗口,功能同上。前端

3.點擊列表中的「刪除」按鈕,彈出刪除數據的詢問窗口,功能以此類推。vue

 

1、添加webpack


 

在「src\mock\member.js」中,增長模擬保存數據的方法:ios

adapters.push(
  (mockAdapter) => mockAdapter.onPost('/api/member/save').reply(req => {
    let promise = new Promise((resolve, reject) => {
      let data = req.data ? JSON.parse(req.data) : {}
      let result = {}
      if (data.name) {
        result.success = true
        result.message = '保存成功'
      } else {
        result.success = false
        result.message = '姓名是必填參數'
      }

      setTimeout(() => {
        resolve([200, result])
      }, 2000)
    })
    return promise
  })
)

 

在src\pages\Member.vue中編寫添加相關的代碼:git

對話框的佈局:github

  <!--對話框-->
  <el-dialog :title="form && form.id ? '編輯' : '新增' " :visible.sync="formVisible" :close-on-click-modal="false">
    <el-form :model="form" label-width="100px" :rules="rules" ref="form">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="性別" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio :label="1"></el-radio>
          <el-radio :label="2"></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click.native="formVisible = false">取消</el-button>
      <el-button type="primary" @click.native="handleSubmit" :loading="formLoading">提交</el-button>
    </div>
  </el-dialog>

 

保存按鈕的代碼:web

let handleSubmit = function() {
  if (this.formLoading)
    return

  this.$refs.form.validate(valid => {
    if (!valid)
      return

    this.formLoading = true

    //調用http協議
    this.$axios.post('/api/member/save', this.form).then(res => {
      this.formLoading = false
      if (!res.data.success) {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: 'error'
        });
        return
      }
      this.$message({
        type: 'success',
        message: '保存成功!'
      })

      //從新載入數據
      this.page = 1
      this.getRows()
      this.formVisible = false
    }).catch(e => this.formLoading = false)
  })
}

 

 

2、修改spring


 

若是完成添加功能,那麼修改的功能就很是簡單,只須要把handleEdit方法修改成:

let handleEdit = function(index, row) {
  this.form = Object.assign({}, row)
  this.formVisible = true
}

注意的是:千萬不要直接給form賦row的值,由於這樣作的話,若是修改了數據但沒有保存,關閉窗口的時候,列表中的數據會被誤修改。Object.assign是克隆row的值,這樣,form對象就是一個副本,怎麼修改都沒問題。

 

3、刪除


 

在「src\mock\member.js」中,增長模擬刪除數據的方法:

adapters.push(
  (mockAdapter) => mockAdapter.onGet(/\/api\/member\/remove\/\w+/).reply(req => {
    let promise = new Promise((resolve, reject) => {
      let result = {
        success: true,
        message: '刪除成功'
      }
      setTimeout(() => {
        resolve([200, result])
      }, 2000)
    })
    return promise
  })
)

 

handleDelete的方法修改成:

let handleDelete = function(index, row) {
  if (this.pageLoading)
    return

  this.$confirm('此操做將永久刪除該數據, 是否繼續?', '提示', {
    confirmButtonText: '肯定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    this.pageLoading = true
    this.$axios.get('/api/member/remove/' + row.id).then(res => {
      this.pageLoading = false
      if (!res.data.success) {
        this.$message({
          type: 'error',
          message: res.data.message
        })
        return
      }
      this.$message({
        type: 'success',
        message: '刪除成功!'
      })
      this.page = 1
      this.getRows()
    }).catch(e => this.pageLoading = false)
  }).catch(e => {})
}

 

 

完整的代碼以下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

import 'font-awesome/css/font-awesome.min.css'

import ElementUI from 'element-ui'
import './assets/theme/element-#0b0a3e/index.css'
Vue.use(ElementUI)

//開發模式開啓mock.js
if (process.env.NODE_ENV === 'development') {
  require('./mock')
}

import axios from 'axios'
Vue.prototype.$axios = axios

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: {
    App
  },
  template: '<App/>'
})
src\main.js

 

import Mock from 'mockjs'

let adapters = []
adapters.push(
  (mockAdapter) => mockAdapter.onPost('/api/member/loadPage').reply(req => {
    let promise = new Promise((resolve, reject) => {
      let data = req.data ? JSON.parse(req.data) : {
        size: 20
      }
      let result = {
        rows: [],
        total: 10000
      }
      for (let i = 0; i < data.size; i++) {
        let item = Mock.mock({
          id: Mock.Random.guid(),
          name: Mock.Random.cname(),
          sex: Mock.Random.integer(1, 2),
          'age|18-30': 1,
          date: Mock.Random.date(),
          address: Mock.mock('@county(true)'),
        })
        result.rows.push(item)
      }
      setTimeout(() => {
        resolve([200, result])
      }, 2000)
    })
    return promise
  })
)

adapters.push(
  (mockAdapter) => mockAdapter.onPost('/api/member/save').reply(req => {
    let promise = new Promise((resolve, reject) => {
      let data = req.data ? JSON.parse(req.data) : {}
      let result = {}
      if (data.name) {
        result.success = true
        result.message = '保存成功'
      } else {
        result.success = false
        result.message = '姓名是必填參數'
      }

      setTimeout(() => {
        resolve([200, result])
      }, 2000)
    })
    return promise
  })
)

adapters.push(
  (mockAdapter) => mockAdapter.onGet(/\/api\/member\/remove\/\w+/).reply(req => {
    let promise = new Promise((resolve, reject) => {
      let result = {
        success: true,
        message: '刪除成功'
      }
      setTimeout(() => {
        resolve([200, result])
      }, 2000)
    })
    return promise
  })
)

export {
  adapters
}
src\mock\member.js

 

<template>
<section>
  <!--工具條-->
  <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
    <el-form :inline="true" :model="filters">
      <el-form-item>
        <el-input v-model="filters.query" placeholder="姓名/手機號等條件" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="handleQuery" icon="el-icon-search">查詢</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="handleAdd" icon="el-icon-plus">添加</el-button>
      </el-form-item>
    </el-form>
  </el-col>
  <el-table :data="rows" style="width: 100%;overflow: auto;" :height="clientHeight" stripe border highlight-current-row v-loading="pageLoading">
    <el-table-column label="註冊日期" width="180">
      <template slot-scope="scope">
       <i class="el-icon-time"></i>
       <span style="margin-left: 10px">{{ scope.row.date }}</span>
     </template>
    </el-table-column>
    <el-table-column label="姓名" width="180" :show-overflow-tooltip="true">
      <template slot-scope="scope">
       <el-popover trigger="hover" placement="top">
         <p>姓名: {{ scope.row.name }}</p>
         <p>住址: {{ scope.row.address }}</p>
         <div slot="reference" class="name-wrapper">
           <el-tag size="medium">{{ scope.row.name }}</el-tag>
         </div>
       </el-popover>
     </template>
    </el-table-column>
    <el-table-column prop="sex" label="性別" width="100" align="center" :show-overflow-tooltip="true">
      <template slot-scope="scope">
        {{scope.row.sex===1?'男':'女'}}
      </template>
    </el-table-column>
    <el-table-column label="操做">
      <template slot-scope="scope">
       <el-button
         size="mini"
         type="primary"
         @click="handleEdit(scope.$index, scope.row)"><i class="el-icon-edit"></i>編輯</el-button>
       <el-button
         size="mini"
         type="danger"
         @click="handleDelete(scope.$index, scope.row)"><i class="el-icon-delete"></i>刪除</el-button>
     </template>
    </el-table-column>
  </el-table>
  <!--底部-->
  <el-col :span="24" class="toolbar">
    <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
    </el-pagination>
  </el-col>

  <!--對話框-->
  <el-dialog :title="form && form.id ? '編輯' : '新增' " :visible.sync="formVisible" :close-on-click-modal="false">
    <el-form :model="form" label-width="100px" :rules="rules" ref="form">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="性別" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio :label="1"></el-radio>
          <el-radio :label="2"></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click.native="formVisible = false">取消</el-button>
      <el-button type="primary" @click.native="handleSubmit" :loading="formLoading">提交</el-button>
    </div>
  </el-dialog>

</section>
</template>

<script>
const rules = {
  name: [{
    required: true,
    message: '請輸入姓名',
    trigger: 'blur'
  }],
  sex: [{
    required: true,
    message: '請選擇性別',
    trigger: 'change'
  }]
}

let data = () => {
  return {
    //頁碼
    page: 1,
    //每頁數量
    size: 20,
    //總數
    total: 0,
    //查詢條件
    filters: {},
    //頁面數據
    rows: [],
    //頁面載入狀態
    pageLoading: false,
    //列表高度
    clientHeight: '100%',
    //表單數據
    form: {},
    //驗證規則
    rules: rules,
    //對話框隱藏狀態
    formVisible: false,
    //表單提交狀態
    formLoading: false
  }
}

let handleAdd = function() {
  this.form = {}
  this.form.sex = 1
  this.formVisible = true
}

let handleEdit = function(index, row) {
  this.form = Object.assign({}, row)
  this.formVisible = true
}

let handleDelete = function(index, row) {
  if (this.pageLoading)
    return

  this.$confirm('此操做將永久刪除該數據, 是否繼續?', '提示', {
    confirmButtonText: '肯定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    this.pageLoading = true
    this.$axios.get('/api/member/remove/' + row.id).then(res => {
      this.pageLoading = false
      if (!res.data.success) {
        this.$message({
          type: 'error',
          message: res.data.message
        })
        return
      }
      this.$message({
        type: 'success',
        message: '刪除成功!'
      })
      this.page = 1
      this.getRows()
    }).catch(e => this.pageLoading = false)
  }).catch(e => {})
}

let getRows = function() {
  if (this.pageLoading)
    return
  this.pageLoading = true

  let params = {
    page: this.page,
    size: this.size,
    query: this.filters.query
  }
  //調用post請求
  this.$axios.post('/api/member/loadPage', params).then(res => {
    this.pageLoading = false
    if (!res.data || !res.data.rows)
      return
    //總數賦值
    this.total = res.data.total
    this.page++;
    //頁面元素賦值
    this.rows = res.data.rows
  }).catch(e => this.pageLoading = false)
}

let handleSubmit = function() {
  if (this.formLoading)
    return

  this.$refs.form.validate(valid => {
    if (!valid)
      return

    this.formLoading = true

    //調用http協議
    this.$axios.post('/api/member/save', this.form).then(res => {
      this.formLoading = false
      if (!res.data.success) {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: 'error'
        });
        return
      }
      this.$message({
        type: 'success',
        message: '保存成功!'
      })

      //從新載入數據
      this.page = 1
      this.getRows()
      this.formVisible = false
    }).catch(e => this.formLoading = false)
  })
}

let handleQuery = function() {
  this.page = 1
  this.getRows()
}

let handleCurrentChange = function(val) {
  this.page = val
  this.getRows()
}

let initHeight = function() {
  this.clientHeight = (document.documentElement.clientHeight - 258) + 'px'
}

export default {
  data: data,
  methods: {
    //查詢
    handleQuery,
    //添加
    handleAdd,
    //修改
    handleEdit,
    //刪除
    handleDelete,
    //頁數改變
    handleCurrentChange,
    //獲取分頁
    getRows,
    //初始化高度
    initHeight,
    //提交數據
    handleSubmit
  },
  mounted: function() {
    window.addEventListener('resize', this.initHeight)
    this.initHeight()
    this.getRows()
  }
}
</script>

<style scoped>
</style>
src\pages\Member.vue

 

 

運行效果以下圖所示:

 

 

好了,到這裏,整個前端的開發就結束了,請咱們期待一塊兒完成後端的開發。

 

 

 

返回目錄

 

git代碼地址:https://github.com/carter659/spring-boot-vue-element.git

 

若是你以爲個人博客對你有幫助,能夠給我點兒打賞,左側微信,右側支付寶。

有可能就是你的一點打賞會讓個人博客寫的更好:)

相關文章
相關標籤/搜索