You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用VueX实现数组元素增删遇问题,求代码排查与修正

问题分析与修复方案

一、删除功能的核心错误

  • 按钮参数传递错误:删除按钮用event.target.value取值,但按钮未设置value属性,实际拿到的是空值。直接把当前遍历的name作为参数传给removeName即可。
  • Vuex mutation名称不匹配:removeName action中提交的是REMOVE-NAME,但mutation定义的是REMOVE_NAME,连字符与下划线不一致,导致mutation无法触发。
  • 数组修改逻辑错误:filter方法仅返回新数组,不会修改原state中的数组,需将过滤后的结果重新赋值给state.list。

二、添加功能的问题

你注释的addName方法逻辑本身没问题,只是当前按钮点击时未传递参数。后续添加输入框后,绑定v-model到响应式变量,点击时传该变量即可。

三、修正后的代码

store.js

import { createStore } from 'vuex'

export default createStore({
  state: () => ({
    list: ['bob', 'joe', 'harry'],
  }),
  getters: {
    listStatus: (state) => state.list,
  },
  actions: {
    addName({ commit }, { name }) {
      commit('ADD_NAME', name)
    },
    removeName({commit}, {name}) {
      // 修正mutation名称,与定义的REMOVE_NAME一致
      commit('REMOVE_NAME', name)
    }
  },
  mutations: {
    ADD_NAME(state, name) {
      state.list.push(name)
    },
    REMOVE_NAME(state, name){
      // 重新赋值原数组,实现删除效果
      state.list = state.list.filter(element => element !== name)
    }
  },
})

userList.vue

<template>
  <div v-for="name in listStatus" :key="name">
    <li>{{ name }}</li>
    <!-- 直接传递当前name给删除方法 -->
    <button @click="removeName(name)">Remove</button>
  </div>
  <!-- 添加输入框示例,绑定响应式变量 -->
  <input v-model="newName" placeholder="输入名称">
  <button @click="addName(newName)">ADD NAME</button>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useStore } from 'vuex'

const store = useStore()
const listStatus = computed(() => store.getters.listStatus)
// 定义响应式变量存储输入框内容
const newName = ref('')

// 接收输入名称并触发添加action
const addName = (input_name) => {
  if(input_name.trim()){ // 简单非空校验
    store.dispatch('addName', { name: input_name })
    newName.value = '' // 清空输入框
  }
}

// 接收要删除的名称并触发删除action
const removeName = (name) => store.dispatch('removeName', { name })
</script>

内容的提问来源于stack exchange,提问作者Eric Andre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:50:37