• Vue如何实现table数据行的新增删除功能
  • 发布于 2个月前
  • 475 热度
    0 评论
  • Fayer
  • 0 粉丝 56 篇博客
  •   

我们在开发管理系统时,数据行的新增和删除操作是最常见的。以前用jQuery开发时,对table数据行的新增,删除操作需要很复杂的DOM操作过程,但是在Vue中,你要实现新增,删除功能可以说是非常简单。今天我们就来看一下在Vue中是如何实现table数据行的新增删除效果的。

1.index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>堆代码 duidaima.com</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
2.main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
3.app.vue
<script setup>
import EmployeeList from './components/Employees/EmployeeList.vue';
</script>
<template>
  <header>
    <div class="wrapper">
    <EmployeeList></EmployeeList>
    </div>
  </header>
  <main>

  </main>
</template>
4.EmployeeList.vue
<script setup>
import { ref } from 'vue';
 const rows =ref([{name:'zhang san ',age:21},{name:'Li si ',age:25}]);
 function addRow()
 {
    this.rows.push({name:'王五 ',age:99});
 }
 function delRow(index)
 {
    this.rows.splice(index,1);
 }
</script>
<template>
<div>
    <div>{{ totalRows }}</div>
    <table>
        <tr>
            <th>ID</th><th>姓名</th><th>年龄</th><th></th>
        </tr>
        <tr v-for="(item,index) in rows" :key="index">
            <td>{{ index }}</td> <td>{{ item.name }}</td><td>{{ item.age }}</td><td>
                <button @click="delRow(index)">删除</button>
            </td>

        </tr>
    </table>
   <button @click="addRow()">新增</button>
</div>
</template>
最终效果:


总结

Vue实现table数据行的新增,删除功能主要技术点如下:

1.删除数据行只要用splice()函数一句就可以搞定

2.新增数据行只要用数组的push()函数就可以搞定

3.要在页面实现动态绑定,需要对数组用ref()函数包裹一下。

这边对Vue中的ref()的用法稍微介绍一下。

在组合式 API 中,推荐使用 ref() 函数来声明响应式状态:

import { ref } from 'vue'
const count = ref(0)
ref() 接收参数,并将其包裹在一个带有 .value 属性的 ref 对象中返回:
const count = ref(0)
console.log(count) // { value: 0 }
console.log(count.value) // 0
count.value++
console.log(count.value) // 1


用户评论