Skip to content
本页目录

用vue-admin-template实现对接增删改查接口

前置条件: 有个增删改查接口

image-20230407173808459

01.准备工作

知道element组件

https://element.eleme.cn/#/zh-CN

下载vue-admin-template

题外话:

ElementAdmin官网

vue-element-admin (gitee.io)

为什么是vue-admin-template?而不是vue-element-admin

因为vue-element-admin太多业务组件,不好改

这个封装了element组件的最基础且必要的页面和逻辑做成了一个后台系统,把vue-admin-template复杂的组件都去掉了可以让我们自由发挥和测试.如登陆,菜单,导航...

image-20230405205429510

image-20230405205605620

下载后解压,并用VSCode打开

image-20230405205819722

在当前目录下载依赖

shell
npm i
// 如果不行 请检查网络 或换成yarn 安装
yarn

终端出现如下就说明已正常运行

image-20230405210219973

启动项目

shell
npm run dev

启动成功

会出现链接

image-20230405210355847

浏览器会打开链接

image-20230405210432475

02.优化项目并接入接口

2.1调整目录

打开router.js文件

image-20230405210628570

调整

image-20230405211009502

效果

image-20230405211108243

2.2调整表格为自己的业务

调整表格为自己的业务

vue
<el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.body }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            Edit
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

调整request的地址 接入自己的api

如何同时保存原来系统的登陆mock和自己的后端api?

image-20230405214139833

修改对应的axios的baseURL

js
const service = axios.create({
  baseURL: 'http://localhost:3000', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

image-20230405221503338

##3.获取全部列表

将api目录下的table修改如下

image-20230405222249377

js
import request from '@/utils/request2'

export function getList(params) {
  return request({
    url: '/api/article',
    method: 'get',
    params
  })
}

并调整table获取接口的逻辑

image-202304052223329704.删除操作

在api/table.js下添加定义删除接口

js

export function deletePosts(data) {
  return request({
    url: '/api/article/' + data.id + '/',
    method: 'delete'
  })
}

并在table.js中引入对应aip

import { getList, deletePosts } from '@/api/table'

添加删除逻辑

js
// 删除操作
    handleDelete(row, index) {
      this.temp = Object.assign({}, row)
      deletePosts(this.temp).then(() => {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })

image-20230405222559335

5.修改操作

在api/table.js下添加定义修改接口

js
export function updatePosts(data) {
  return request({
    url: '/api/article/' + data.id + '/',
    method: 'put',
    data
  })
}

并在table.js中引入对应aip

import { getList, deletePosts, updatePosts  } from '@/api/table'

在table.js中定义data

vue
  data() {
    return {
      list: null,
      listLoading: true,
      textMap: { // 表示编辑或新增的变量
        update: 'Edit',
        create: 'Create'
      },
      dialogFormVisible: false, // 表示显示
      dialogStatus: '', // 表示弹窗状态
      rules: { // 表单校验规则
        title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        body: [{ required: true, message: 'body is required', trigger: 'blur' }]
      },
      temp: { // 表示表单的临时变量
        id: undefined,
        title: '',
        body: ''
      }
    }
  },

弹窗表格(包含编辑和新增)可以复用

vue
    <!-- 弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">

        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="内容" prop="body">
          <el-input v-model="temp.body" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>

点击修改的逻辑

js
 // 修改
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

点击确认修改

js
  // 点击确认
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updatePosts(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }

6.新增操作

在api/table.js下添加定义新增接口

js
export function addPosts(data) {
  return request({
    url: '/api/article/',
    method: 'post',
    data
  })
}

并在table.js中引入对应aip

import { getList, deletePosts, updatePosts, addPosts  } from '@/api/table'

新增按钮和操作

vue
<el-button type="primary" @click="handleCreate">+新增</el-button>

对应的逻辑(与修改类似)

js
    // 重置临时变量
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        body: ''
      }
    },
    // 新增操作
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 点击确认
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addPosts(this.temp).then(() => {
            this.list.push(this.temp) // 新增
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }

7.查询操作

在api/table.js下添加定义新增接口

js
export function searchPosts(data) {
  return request({
    url: '/api/article/title/' + data.title + '/',
    method: 'get'
  })
}

并在table.js中引入对应aip

import { getList, deletePosts, updatePosts, addPosts, searchPosts } from '@/api/table'

在data中新增变量

searchTemp: {
	title: ''
}

添加搜索框

vue
 <div>
 <el-input v-model.trim="searchTemp.title" placeholder="请输入内容" @change="searchTitle" />
 {{ searchTemp.title }}
 </div>

对应逻辑

js
// 查询
    searchTitle(value) {
      this.listLoading = true
      if (value === '') {
        this.fetchData()
      } else {
        searchPosts(this.searchTemp).then(response => {
          this.list = response.data
          this.listLoading = false
        })
      }