在vue.js里实现实现人员列表包含搜索、新增人员、编辑、删除功能代码
时间: 2024-10-11 11:12:10 浏览: 64
在Vue.js中,你可以通过组件化的方式来实现这样一个人员列表功能,结合Vuex管理状态和事件总线。这里是一个简化的示例:
首先,创建一个`PersonList.vue`组件,它将显示人员列表并提供搜索功能:
```html
<template>
<div>
<input v-model="search" placeholder="Search">
<ul>
<li v-for="person in filteredPeople" :key="person.id">
{{ person.name }}
<!-- 添加编辑和删除按钮 -->
<button @click.prevent="edit(person)">编辑</button>
<button @click.prevent="delete(person)">删除</button>
</li>
</ul>
<PersonForm @add="addPerson"></PersonForm>
</div>
</template>
<script>
import PersonForm from './PersonForm.vue';
export default {
components: { PersonForm },
data() {
return {
search: '',
people: [], // 假设这是从API获取的数据
};
},
computed: {
filteredPeople() {
return this.people.filter((person) => person.name.includes(this.search));
}
},
methods: {
edit(person) {
// 跳转到编辑页面或者打开模态框
},
delete(person) {
this.$store.dispatch('deletePerson', person);
},
addPerson(newPerson) {
this.$store.dispatch('addPerson', newPerson);
},
},
};
</script>
```
然后,创建一个`PersonForm.vue`组件,用于添加新人员:
```html
<template>
<form @submit.prevent="onSubmit">
<!-- 输入框和提交按钮 -->
</form>
</template>
<script>
export default {
methods: {
onSubmit() {
// 提交数据到Vuex store 或 API
this.$emit('add', { name: '新人员' });
},
},
};
</script>
```
最后,设置Vuex的状态和actions,例如在`store/index.js`中:
```javascript
import Vue from 'vue';
import Vuex from 'vuex';
const state = {
people: [],
};
const mutations = {
ADD_PERSON(state, payload) {
state.people.push(payload);
},
DELETE_PERSON(state, payload) {
const index = state.people.findIndex((person) => person.id === payload.id);
if (index !== -1) {
state.people.splice(index, 1);
}
},
};
const actions = {
addPerson({ commit }, payload) {
commit('ADD_PERSON', payload);
},
deletePerson({ commit }, payload) {
commit('DELETE_PERSON', payload);
},
};
export default new Vuex.Store({
state,
mutations,
actions,
});
```
阅读全文