vue3+elementplus(vuex)增删改查

我心飞翔 分类:vue
vue3+elementplus(vuex)增删改查

bug收集:专门解决与收集bug的网站

网址:www.bugshouji.com

最近写了个 vue3+element plus(vuex) 实现的增删改查

分享下相关的一些技术点

(如有源码需要,可私信发留言)

1、项目架构搭建

vue3+elementplus(vuex)增删改查

2. 组件结构

vue3+elementplus(vuex)增删改查

3. element-plus引入

下载

npm install element-plus

main.js中引入

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
createApp(App).use(router).use(store).use(ElementPlus).mount('#app')

4. columns 列名的配置信息

在设置columns属性时,其中的宽度字段(width)必须设置值(只能是数字类型)且每一列都要设置,不然会出现数据不显示或是只显示一列的情况。

const columns = [
{
    key: "id",
    dataKey: "id",//需要渲染当前列的数据字段,如{id:9527,name:'Mike'},则填id
    title: "id",//显示在单元格表头的文本
    width: 80,//当前列的宽度,必须设置
fixed: true//是否固定列
},
{
    key: "name",
    dataKey: "name",//需要渲染当前列的数据字段,如{id:9527,name:'Mike'},则填name
    title: "姓名",
    width: 100,
fixed: true
}]

5. 自定义单元格内容

自定义单元格渲染器的字段是cellRenderer,类型为VueComponent /(props: CellRenderProps) => VNode

方法一: h 函数实现:

import { ref, h } from "vue";
import { ElMessageBox, ElMessage, ElButton ,ElTag} from "element-plus";
//columns 是一个数组,里面的值为每一列的配置信息
const columns = [
 {
            key: "state",
            dataKey: "state",
            title: "状态",
            width: 80,
            cellRenderer: ({ cellData }) =>
            h(
                ElTag,
                { type: cellData == "1" ? "success" : "danger" },
                { default: () => cellData == "1" ? "有效" : "无效" }//也可以写成字符串如'这是标签内容',但控制台会有警告
            )
 }
]

方法二:jsx实现

使用jsx的方式就比较简捷了,需要在script标签设置lang属性等于jsx,
在cellRenderer函数中可以直接使用jsx的语法和UI组件(还有自定义组件)

 const columns = [{
            key: "handle",
            title: "操作",
            width: 200,
            align: "center",
            cellRenderer: ({rowData}) => (
            <>
                <el-button
                type="danger"
                icon={Delete}
                onClick={handleDelete.bind(this, rowData.admin_no)}
                >
                删除
                </el-button>
                <el-button
                type="primary"
                icon={Edit}
                onClick={handleUpdate.bind(this, rowData.admin_no)}
                >
                修改
                </el-button>
            </>
            ),
        }]

6. icon 的显示的配置

因 element-plus/icons改变成了svg ,故显示 icon 需要进行如下配置:

1. 安装 @element-plus/icons-vue

npm install @element-plus/icons-vue

2. 使用

在引用图标的页面中将要使用的图标引入,作为js对象,代码如下:

<script>
import { Edit,Share } from "@element-plus/icons-vue";
export default {
    setup() {
return {
       Edit,
       Share
     }
    }
   }
</script>

使用方式和elemunt-ui3官网一致

<div class="flex">
<el-button type="primary" :icon="Edit" />
<el-button type="primary" :icon="Share" />
<el-button type="primary">
     Upload<el-icon class="el-icon--right"><Upload /></el-icon>
</el-button>
</div>

7. 相关hook

1. useRouter() 获取路由对象

import { useRouter } from 'vue-router' //引入
const router = useRouter();  //获取router对象
 router.push("/login");  //跳转
 router.push({  //跳转带参数
            name: 'adminmodify',
            query: {
                id
            }
        });

  1. useRoute() 获取当前路由对象
import { onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
const route = useRoute();
onMounted(() => {
//加载时,显示对应的数据
const id = route.query.id;
});

3. useStore 使用vuex的hook

import { useStore } from 'vuex'
const { getters, dispatch } = useStore();

8. hooks 文件夹

hooks 文件夹中的文件,主要是将对应逻辑封装在一个文件中

完整代码如下:

import service from './../service/index'
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

function adminManage() {
    const router = useRouter();
    const store = useStore();
    console.log(store);
    async function getAdminInfoById(id) {
        const {data} = await service.admin.getAdminInfoById(id);
        console.log("data",data);
        if (data.code == 200) {
            return data.data;
        } else if (data.code == 201) {
            router.push("/login"); // 跳转到登录
            return null;
        } else {
            //提示错误信息
            ElMessage({
                message: data.message,
                type: 'error',
            });
            return null;
        }

    }
    //获取数据,根据searchName,currentPage,pageSize  
    function getAdminListBySearchAndPage() {
        service.admin.getAdminListBySearchAndPage({
            currentPage: store.state.admin.currentPage,
            pageSize: store.state.admin.pageSize,
            searchName: store.state.admin.searchName
        }).then(({ data }) => {
            if (data.code == 200) {
                console.log(data.data);
                store.dispatch("admin/setAdminData", data.data);
            } else if (data.code == 201) {
                console.log(data.message);
                router.push("/login"); // 跳转到登录
            } else {
                console.log(data);
                //提示错误信息
                ElMessage({
                    message: data.message,
                    type: 'error',
                });
            }
        })
    }
    // 根据searchName获取总条数
    function getAdminListBySearchCount() {
        service.admin.getAdminListBySearchCount({
            searchName: store.state.admin.searchName
        }).then(({ data }) => {
            if (data.code == 200) {
                store.dispatch("admin/setTotalSize", data.data);
            } else if (data.code == 201) {
                router.push("/login"); // 跳转到登录
            } else {
                //提示错误信息
                ElMessage({
                    message: data.message,
                    type: 'error',
                });
            }
        })
    }
    // 删除方法,根据id
    function Handle_del(id) {
        //发起请求
        service.admin.delAdminById(id).then(({ data }) => {
            if (data.code == 200) { //获取成功
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                });
                // 重新获取数据,与总条数
                getAdminListBySearchAndPage();
                getAdminListBySearchCount();
            } else if (data.code == 201) {
                router.push("/login"); // 跳转到登录
            } else {
                //提示错误信息
                ElMessage({
                    message: data.message,
                    type: 'error',
                });
            }
        })
    }
    // 管理员登录 
    function adminLogin(user, pwd) {
        service.admin.admin_login(user, pwd).then(({ data }) => {
            if (data.code == 200) {
                router.push("/index"); // 跳转到登录
                //存储登录用户的信息在vuex中
            } else {
                ElMessage({
                    message: data.message,
                    type: 'error',
                });
            }
        })
    }
    // 添加管理员
    function add_admin(userInput) {
        service.admin.add_admin(userInput).then(({ data }) => {
            if (data.code == 200) {
                ElMessage({
                    message: data.message,
                    type: 'success',
                });
                router.push("/index"); //跳到列表页
            }
            else if (data.code == 201) {
                router.push("/login"); // 跳转到登录
            }
            else {
                ElMessage({
                    message: data.message,
                    type: 'error',
                });
            }
        })
    }
    //更新管理
    function update_admin(userInput){
        service.admin.updateAdminInfoById(userInput).then(({ data }) => {
            if (data.code == 200) {
                ElMessage({
                    message: data.message,
                    type: 'success',
                });
                router.push("/index"); //跳到列表页
            }
            else if (data.code == 201) {
                router.push("/login"); // 跳转到登录
            }
            else {
                ElMessage({
                    message: data.message,
                    type: 'error',
                });
            }
        })
    }

    return {
        getAdminListBySearchAndPage,
        getAdminListBySearchCount,
        getAdminInfoById,
        Handle_del,
        adminLogin,
        add_admin,
        update_admin
    }
}

export default adminManage

(如有源码需要,可私信发留言)


苟有恒 , 何必三更眠五更起

回复

我来回复
  • 暂无回复内容