vue-cli3+axios+element实现调用后端接口实现表格的增删改查

成品图

先上代码
<template>
    <div id="app">
        <el-row>
            <el-col :span="8" :offset="6">
                <el-input placeholder="请输入关键字" icon="search" v-model="search"></el-input>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="dialogVisible = true">添加</el-button>
                <el-button @click="getData"></el-button>
            </el-col>
        </el-row>
        <el-table
                :data="tables"
                border
                style="width: 100%">
            <el-table-column
                    prop="fatherName"
                    label="父类别名称"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="name"
                    label="类别名称"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="description"
                    label="类别描述">
            </el-table-column>
            <el-table-column
                    prop="done"
                    label="操作">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            style="margin-right: 20px"
                            @click="editTableData(scope.$index)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%">
            <el-row>
                父类别名称 :
                <el-select v-model="value" value="">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-row>
            <el-row>
                类别名称:
                <el-input v-model='productName' style="width: 70%;margin: 10px 0 10px 0"></el-input>
            </el-row>
            <el-row>
                类别描述:
                <el-input v-model='productDescription' style="width: 70%"></el-input>
            </el-row>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addData">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog
                title="提示"
                :visible.sync="dialogVisibleb"
                width="30%">
            <el-row>
                父类别名称 :
                <el-select v-model="value" value="">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-row>
            <el-row>
                类别名称:
                <el-input v-model='productNameb' style="width: 70%;margin: 10px 0 10px 0"></el-input>
            </el-row>
            <el-row>
                类别描述:
                <el-input v-model='productDescriptionb' style="width: 70%"></el-input>
            </el-row>
            <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleb = false">取 消</el-button>
    <el-button type="primary" @click="updateData">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>
    import ajax from '../ajax';

    export default {
    
    
        name: 'home',
        data() {
    
    
            return {
    
    
                tableData: [],
                options: [{
    
    
                    value: '选项1',
                    label: '黄金糕'
                }, {
    
    
                    value: '选项2',
                    label: '双皮奶'
                }, {
    
    
                    value: '选项3',
                    label: '蚵仔煎'
                }, {
    
    
                    value: '选项4',
                    label: '龙须面'
                }, {
    
    
                    value: '选项5',
                    label: '北京烤鸭'
                }],
                value: '',
                search: '',
                dialogVisible: false,
                dialogVisibleb: false,
                visible: false,
                productName: '',
                productDescription: '',
                productNameb: '',
                productDescriptionb: '',
                _index: ''
            };
        },
        computed: {
    
    
            //查询
            tables() {
    
    
                if (this.search) {
    
    
                    return this.tableData.filter(item =>
                        Object.keys(item).some(key =>
                            String(item[key]).toLowerCase().indexOf(this.search) > -1
                        )
                    );
                } else return this.tableData;
            }
        },
        methods: {
    
    
            editTableData(index) {
    
    
                this.dialogVisibleb = true;
                this._index = index;
            },
            //添加
            addData() {
    
    
                this.dialogVisible = false;
                ajax({
    
    
                    url: '/goods/category',
                    method: 'post',
                    data: {
    
    
                        'description': this.productDescription,
                        'name': this.productName,
                        'parentId': 0,
                    }
                }).then(res => {
    
    
                    this.getData();
                }).catch(error => {
    
    
                    console.log(error);
                });
            },
            //删除
            handleDelete(index) {
    
    
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    
    
                    beforeClose: (action, instance, done) => {
    
    
                        if (action === 'confirm') {
    
    
                            instance.confirmButtonLoading = true;
                            ajax({
    
    
                                url: '/goods/category',
                                method: 'delete',
                                params: {
    
    
                                    'categoryId': this.tableData[index].resDataId,
                                }
                            }).then(res => {
    
    
                                this.getData();
                            }).catch(error => {
    
    
                                console.log(error);
                            });
                            done();
                            instance.confirmButtonLoading = false;
                        } else {
    
    
                            done();
                        }
                    }
                });
                this.visible = false;
            },
            //修改
            updateData() {
    
    
                ajax({
    
    
                    url: '/goods/category',
                    method: 'put',
                    data: {
    
    
                        'categoryId': this.tableData[this._index].resDataId,//this.tableData[this._index].resDataId
                        'description': this.productDescriptionb,
                        'name': this.productNameb,
                        'parentId': 0,
                    }
                }).then(res => {
    
    
                    this.getData();

                }).catch(error => {
    
    
                    console.log(error);
                });
                this.dialogVisibleb = false;
            },
            getData() {
    
    
                ajax({
    
    
                    url: '/goods/category',
                    method: 'get',
                }).then(res => {
    
    
                    this.tableData.splice(0, this.tableData.length);
                    const resData = res.data.data.data;
                    resData.forEach((items) => {
    
    
                        if(items.delete === false){
    
    
                            this.tableData.push({
    
    
                                'name': items.name,
                                'description': items.description,
                                'resDataId': items.categoryId
                            });
                        }
                    });
                }).catch(error => {
    
    
                    console.log(error);
                });
            }
        },
    };

实现请求后台API接口使用的是axios
由于我的后台接口需要根据接口需要,使用了自定义axios实例的方法,在上面的链接中有具体例子,我将axios的实例封装到ajax.js的文件中,后续的调用均使用的是ajax(只是个名字),下面是我ajax.js的代码

import axios from 'axios';
import Cookies from 'js-cookie';
const ajax = axios.create({
    
    
    baseURL: '/apis/',
    timeout: 120000,
    withCredentials: true,
    headers: {
    
    
        token: *****
        appId: *****
    },
});
export default ajax;

相关的参数在链接中说的很清楚,不明白的可以去查阅文档。要注意你的项目中已经npm install axios 和 js-cookie。
写道这里就已经可以发送请求了,但是还会出现跨域的问题,这时候就需要在config.js中配置一下代理,由于vue-cli3移除了config.js文件,因此我们需要自己创建一个,需要创建在项目的根目录下。具体如何配置可以vue-cli配置参考
下面给出我的vue.config.js代码(文件名必须带上vue)

module.exports = {
    
    
    devServer: {
    
    
        proxy: {
    
    
            '/apis':{
    
    
                pathRewrite: {
    
     '^/apis': '' },
                target: 'http://你要代理的计算机域名',
                changOrigin: true
            }
        },
        disableHostCheck: true, 
    }
};

这里解释一下最后的 disableHostCheck: true, 由于我这里的后端请求数据需要需要一个cooke值来验证,当时解决的方法是修改了hosts。但是这样就不能通过webpack-dev-server的安全检查,所以就需要设置这一句来取消host检查。

到这里,就已经可以请求到数据了。接下来就是对数据经行处理并渲染到页面上,这里记录我遇到的几个问题。

1.修改操作的时候,需要获取到当前那一行的索引,由于使用了element中的el-dialog对话弹窗,如果直接使用scope.$index无法获取到索引,因此在data中设置_index属性,用editTableData方法将索引赋值给_index在在修改方法中通过this._index来获取某一行的索引。

editTableData(index) {
                this.dialogVisibleb = true;
                this._index = index;
            },

2.在实现删除功能的时候,使用的请求方法是delete,平时并没有接触到这个请求,一般都是get+post就解决了,开始请求一直报500的错,后来了解了之后才知道detele传参方法和get相同,put和post传参方法相同。

3.删除按钮不要使用el-popover组件来实现,在有多个标签的时候,他们会共用一个visible,当点击框外的时候,这个组件会默认visible: false,就会导致弹出失效。我后来使用了MessageBox。

猜你喜欢

转载自blog.csdn.net/e1172090224/article/details/96150416