vue 实现删除传值
Vue 实现删除传值的方法
父子组件传值删除
在父组件中定义数据和方法,通过props传递给子组件,子组件触发删除操作后通过$emit通知父组件更新数据。
父组件代码示例:
<template>
<child-component :list="list" @delete-item="handleDelete"></child-component>
</template>
<script>
export default {
data() {
return {
list: ['item1', 'item2', 'item3']
}
},
methods: {
handleDelete(index) {
this.list.splice(index, 1)
}
}
}
</script>
子组件代码示例:
<template>
<div v-for="(item, index) in list" :key="index">
{{ item }}
<button @click="deleteItem(index)">删除</button>
</div>
</template>
<script>
export default {
props: ['list'],
methods: {
deleteItem(index) {
this.$emit('delete-item', index)
}
}
}
</script>
Vuex状态管理删除
对于大型应用,可以使用Vuex集中管理状态,通过mutations来修改数据。
store.js示例:
const store = new Vuex.Store({
state: {
items: ['item1', 'item2', 'item3']
},
mutations: {
DELETE_ITEM(state, index) {
state.items.splice(index, 1)
}
}
})
组件中使用:

methods: {
deleteItem(index) {
this.$store.commit('DELETE_ITEM', index)
}
}
事件总线跨组件删除
对于非父子关系的组件,可以使用事件总线实现通信。
创建事件总线:
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
发送事件组件:

import { EventBus } from './event-bus.js'
methods: {
deleteItem(index) {
EventBus.$emit('delete-item', index)
}
}
接收事件组件:
import { EventBus } from './event-bus.js'
created() {
EventBus.$on('delete-item', index => {
this.list.splice(index, 1)
})
}
使用provide/inject
对于深层嵌套组件,可以使用provide/inject传递删除方法。
祖先组件:
provide() {
return {
deleteItem: this.handleDelete
}
},
methods: {
handleDelete(index) {
this.list.splice(index, 1)
}
}
后代组件:
inject: ['deleteItem'],
methods: {
delete(index) {
this.deleteItem(index)
}
}






