【 Vue3 + Vite + setup语法糖 + Pinia + VueRouter + Element Plus 第三篇】(持续更新中)

本文介绍了如何在Vue3中使用setup语法糖和ElementPlus库来实现表格的增删改查功能,包括封装axios请求、环境变量配置和模糊查询组件。此外,还讨论了VueRouter的使用,如路由跳转、路由信息获取及权限路由配置,为项目构建提供了基础架构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在第二篇我们主要学习了@路径别名,配置.env环境变量,封装axios请求,以及使用api获取数据后渲染 Element Plus表格

本期需要掌握的知识如下:

  • 封装列表模糊查询组件
  • 实现新增 编辑 删除 模糊查询 重置 功能
  • 实现表单校验功能
  • 实现组件间传值

下期需要掌握的知识如下:

  • 项目中导入 VueRouter
  • 使用 VueRouter 完成路由跳转、获取路由信息
  • VueRouter 模块化路由拦截器
  • 权限路由配置

本期实现效果如下:

简单做个梳理

  1. 创建 table 表格,第二篇文章已经讲过,没看过的请看上一篇文章
  2. 封装 新增 / 编辑弹窗组件
  3. 封装 模糊查询组件
1. home页 , table表格以及要封装的 模糊查询组件 弹窗组件在此体现
<div class="home">
    <div class="table-title">
      Vue3 + setup 语法糖 + Element Plus 实现 table 增删改查
    </div>
    <div class="table-content">
      <!-- 模糊查询组件 -->
      <searchComponent @hanleSearchTable="hanleSearchTable" @handleAdd="handleAdd" />
      <!-- table -->
      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column v-for="{id,prop,label} in tableColumn" :prop="prop" :key="id" :label="label" :width="label=='序号' ? 100 :''" align="center" />
        <el-table-column fixed="right" label="操作" align="center" width="240">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handlEmodify(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="handleDel(scope.row)">删除</el-button>
            <el-button link type="primary" size="small" @click="handlDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增 / 编辑弹窗组件 -->
    <rowFrom ref="rowFromComponent" @submitFrom="submitFrom" />
  </div>
解释说明

searchComponentrowFrom 都是封装的子组件

组件上所看到的 @hanleSearchTable都是子组件触发父组件的方法, = 前是子组件方法名, =后为当前组件也就是home页面的方法

import { ref, onMounted, defineComponent } from 'vue'
import { useRouter } from 'vue-router'
import { MessageBoxMixins } from '@/mixin'
import { ElMessage } from 'element-plus'
import { getTableList } from '@/api/home.js'
import rowFrom from './components/rowForm.vue'
import searchComponent from './components/search.vue'


/**
 * @type component
 * @description 在此注册组件
 * **/

const Component = defineComponent({
  rowFrom, searchComponent
})


/**
 * @type data
 * @description 所有数据都在此体现
 * **/

const tableData = ref([])
const dialogTitle = ref('添加')
const rowFromComponent = ref(null)
const Router = useRouter()
const tableColumn = ref([
  { id: 1, prop: 'id', label: '序号' },
  { id: 2, prop: 'date', label: '时间' },
  { id: 3, prop: 'name', label: '姓名' },
  { id: 4, prop: 'address', label: '地址' }
])

/**
 * @type 生命周期
 * @description 所有生命周期函数都在此体现
 * **/

onMounted(() => {
  initTable()
})


/**
* @type methods
* @description 所有方法、事件都在此层中体现
* **/

// 初始化表格
const initTable = async () => {
  let res = await getTableList()
  ElMessage.success('获取成功')
  if (res.data) return tableData.value = res.data
}

// 子组件触发父组件模糊查询方法
const hanleSearchTable = (searchData) => {
  if (!searchData) return initTable()
  if (searchData.date != null && searchData.date != '') {
    let filterTableList = tableData.value.filter(item => { if (item.date == searchData.date) return item })
    tableData.value = filterTableList
  } else {
    initTable()
  }
}

// 添加按钮点击事件
const handleAdd = () => {
  if (dialogTitle !== '添加') {
    dialogTitle.value = '添加'
  }
  // 在此触发子组件方法并传参
  rowFromComponent.value.childMethod(null, dialogTitle.value)
}
// 编辑按钮点击事件
const handlEmodify = row => {
  if (dialogTitle !== '修改') {
    dialogTitle.value = '修改'
  }
  // 调用子组件方法同时,将数据转换为非响应式
  rowFromComponent.value.childMethod(JSON.parse(JSON.stringify(row)), dialogTitle.value)
}
// 删除按钮点击事件
const handleDel = async row => {
	// MessageBoxMixins 封装的公共按钮提示组件  可先注释该两行代码
  let res = await MessageBoxMixins('确认删除该条数据?删除后不可恢复')
  if (res !== 'confirm') return false
  tableData.value = tableData.value.filter(item => { if (item.id !== row.id) return item })
}
// 查看按钮点击事件
const handlDetail = row => {
  if (!row.id) return ElMessage.error('缺少id')
}


// 子组件弹窗确认按钮触发父组件的事件函数
const submitFrom = (val, type) => {
  if (type == 'add') {
    const id = tableData.value.length + 1
    let newRow = Object.assign({ id }, val)
    tableData.value = [...tableData.value, newRow]
  } else {
    tableData.value.forEach((item, index) => {
      if (item.id == val.id) {
        tableData.value[index] = val
      }
    })
  }
  // 调用子组件方法关闭弹窗
  rowFromComponent.value.btnCancel()
}


新增、编辑弹窗封装

在当前文件夹下新建 components 目录,并在该目录下新建 rowForm.vue 文件

后面的模糊搜索组件也是如此 不再过多解释

在这里插入图片描述

  • dialogTableVisible 控制弹窗打开或关闭
  • dialogTitle 弹窗标题 这里使用变量的方式是为了区分 新增/编辑
  • close-on-click-modal 点击空白区域不允许关闭弹窗
  • row 当前表单绑定的对象
  • rules 表单校验规则
<el-dialog v-model="dialogTableVisible" :title="dialogTitle + '数据'" :close-on-click-modal="false" style="width:40%;">
    <el-form :rules="rules" :model="row" label-width="80px" ref="ruleFrom">
      <el-form-item label="时间:" prop="date">
        <el-date-picker style="width:100%;" value-format="YYYY-MM-DD" v-model="row.date" type="date" placeholder="请选择时间" />
      </el-form-item>
      <el-form-item label="姓名:" prop="name">
        <el-input v-model="row.name" autocomplete="off" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="地址:" prop="address">
        <el-input v-model="row.address" autocomplete="off" placeholder="请输入地址" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="btnSure">确认</el-button>
      </span>
    </template>
  </el-dialog>
  

别忘了 script 标签带 setup语法糖

在这里插入图片描述

import { ref } from 'vue';

/**
 * @type data
 * @description 所有数据都在此体现
 * **/

// 控制弹窗打开/关闭 默认为 false
const dialogTableVisible = ref(false)
// 初始化当前表单
const row = ref({})
// 初始化 弹窗 title
const dialogTitle = ref(null)

// 获取refs元素,常量名称与ref保持一致 后边表单校验会用到
const ruleFrom = ref(null)

// 表单校验规则
const rules = {
  name: { required: true, message: "姓名不能为空!", trigger: "blur" },
  date: { required: true, message: "时间不能为空!", trigger: "change" },
  address: { required: true, message: "地址不能为空!", trigger: "blur" }
}


/**
* @type methods
* @description 所有方法、事件都在此层中体现
* **/

//在此注册触发父组件的方法
// 无需手动引入 defineEmits ,直接使用即可,传参必须为数组
const emit = defineEmits(['submitFrom'])

// 父组件调用此组件修改弹窗的标题、是否打开、以及表单数据
const childMethod = (data, title) => {
  dialogTitle.value = title
  row.value = data ? data : {}
  dialogTableVisible.value = true
  setTimeout(() => {
    ruleFrom.value.clearValidate()
  }, 0)
}

// 弹窗按钮确认事件
const btnSure = async () => {
  try {
   // 表单校验功能在此 所以要提前获取 ref元素 (ruleFrom)
    await ruleFrom.value.validate()
    if (dialogTitle.value == '添加') {
      // 在此触发父组件的方法 用来修改/添加 tableList
      emit('submitFrom', row.value, 'add')
    } else {
      emit('submitFrom', row.value, 'update')
    }
  } catch (err) {
    console.log('err' + err);
  }
}
// 弹窗按钮取消事件
const btnCancel = () => {
  dialogTableVisible.value = false
}

// 暴露组件方法以供父组件调用
defineExpose({
  childMethod,
  btnCancel
});

模糊查询组件封装

<template>
  <div class="search">
    <div class="search-content">
      <el-form :inline="true" :model="searchData" class="demo-form-inline">
        <el-form-item label="请选择时间:">
          <el-date-picker value-format="YYYY-MM-DD" v-model="searchData.date" type="date" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">新增</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="default" @click="handleResert">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
import { ref } from 'vue'

/**
 * @type data
 * @description 所有数据都在此体现
 * **/

const searchData = ref({
  date: ''
})


/**
 * @type methods
 * @description 所有方法、事件都在此层中体现
 * **/

//在此注册触发父组件的方法
const emit = defineEmits(['hanleSearchTable', 'handleAdd'])

// 新增按钮
const handleAdd = () => {
 // 直接去触发父组件 handleAdd 方法
 // 让父组件再去触发 新增弹窗的方法
  emit('handleAdd')
}
//  查询按钮
const handleQuery = () => {
  // 这里同样如此 不过需要携带查询参数
  emit('hanleSearchTable', searchData.value)
}

// 重置按钮
const handleResert = () => {
  searchData.value = {}
  emit('hanleSearchTable', null)
}
### 项目布局实现 以下是基于 ViteVue3PiniaVue-Router@4、TypeScript 和 `setup` 语法构建项目的具体方法: #### 1. 初始化项目并安装依赖 通过 Vite 创建一个新的 Vue3 项目,并指定 TypeScript 支持: ```bash npm create vite@latest my-project --template vue-ts cd my-project ``` 随后,安装必要的依赖项,包括 Vue Router v4 和 Pinia: ```bash npm install vue-router@4 pinia element-plus axios ``` #### 2. 配置 Element Plus 的按需加载 为了优化打包体积,推荐使用插件来实现 Element Plus 的按需导入。可以安装 `unplugin-vue-components` 和 `unplugin-auto-import` 插件: ```bash npm install unplugin-vue-components unplugin-auto-import -D ``` 在 `vite.config.ts` 中配置这些插件: ```typescript import { defineConfig } from &#39;vite&#39; import vue from &#39;@vitejs/plugin-vue&#39; import AutoImport from &#39;unplugin-auto-import/vite&#39; import Components from &#39;unplugin-vue-components/vite&#39; import { ElementPlusResolver } from &#39;unplugin-vue-components/resolvers&#39; export default defineConfig({ plugins: [ vue(), AutoImport({ resolvers: [ElementPlusResolver()], }), Components({ resolvers: [ElementPlusResolver()], }), ], }) ``` 这一步实现了 Element Plus 组件和 API 的自动导入[^1]。 #### 3. 设置路由管理器 创建 `src/router/index.ts` 文件以定义路由逻辑: ```typescript import { createRouter, createWebHistory } from &#39;vue-router&#39;; import routes from &#39;./routes&#39;; const router = createRouter({ history: createWebHistory(), routes, }); // 路由守卫:验证用户身份 router.beforeEach((to, from, next) => { const token = localStorage.getItem(&#39;token&#39;); const isAuthenticated = !!token; if (to.name === &#39;login&#39;) { localStorage.clear(); } if (to.name !== &#39;login&#39; && !isAuthenticated) { next({ name: &#39;login&#39; }); } else { next(); } }); export default router; ``` 同时,在同一目录下创建 `routes.ts` 定义具体的路由映射表: ```typescript import { RouteRecordRaw } from &#39;vue-router&#39;; const routes: Array<RouteRecordRaw> = [ { path: &#39;/&#39;, component: () => import(&#39;@/views/Home.vue&#39;), name: &#39;home&#39; }, { path: &#39;/login&#39;, component: () => import(&#39;@/views/Login.vue&#39;), name: &#39;login&#39; }, ]; export default routes; ``` #### 4. 整合状态管理工具 Pinia 初始化 Pinia 并将其挂载至应用实例中。编辑 `src/main.ts` 文件如下: ```typescript import { createApp } from &#39;vue&#39;; import App from &#39;./App.vue&#39;; import router from &#39;./router&#39;; import pinia from &#39;./stores&#39;; // 引入 Pinia 实例 import &#39;element-plus/dist/index.css&#39;; const app = createApp(App); app.use(pinia); app.use(router); app.mount(&#39;#app&#39;); ``` 接着,在 `src/stores/` 下创建存储模块文件(如 `userStore.ts`),用于管理全局状态: ```typescript import { defineStore } from &#39;pinia&#39;; export const useUserStore = defineStore(&#39;user&#39;, { state: () => ({ username: &#39;&#39;, isLoggedIn: false, }), actions: { login(username: string) { this.username = username; this.isLoggedIn = true; }, logout() { this.username = &#39;&#39;; this.isLoggedIn = false; }, }, }); ``` #### 5. 构建基础布局结构 修改 `src/App.vue` 来支持动态视图渲染以及顶部导航栏等功能: ```html <template> <div id="app"> <!-- 导航 --> <nav-bar /> <!-- 动态内容区域 --> <router-view></router-view> <!-- 底部版权信息 --> <footer-component /> </div> </template> <script setup lang="ts"> import NavBar from &#39;@/components/NavBar.vue&#39;; import FooterComponent from &#39;@/components/Footer.vue&#39;; </script> ``` #### 6.组件中使用路由与状态管理功能 假设有一个按钮点击事件触发跳转或者更新状态的操作,可以在任何组件内部这样写: ```typescript <script setup lang="ts"> import { useRouter, useRoute } from &#39;vue-router&#39;; import { useUserStore } from &#39;@/stores/userStore&#39;; const userStore = useUserStore(); const router = useRouter(); function handleLoginClick() { userStore.login(&#39;John Doe&#39;); // 更新 Pinia 状态 router.push(&#39;/dashboard&#39;); // 执行页面跳转 } </script> ``` 以上即完成了整个基于 ViteVue3PiniaVue-Router@4、TypeScript 及 Setup 语法的项目布局设计[^2]。 ---
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端大斗师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值