【问题标题】:Vuex is only removing the first elementVuex 只删除第一个元素
【发布时间】:2018-01-12 13:52:12
【问题描述】:

我有以下设置,尝试使用DELETE_NOTE 突变从notes 数组中删除activeNote。但它只删除了数组的第一个元素。

mutations.js 是:

export const mutations = {
  DELETE_NOTE (state) {
    console.log(state.activeNote) // here the activeNote is the correctly selected note
    if (typeof state.notes !== 'undefined' && state.notes.length > 0) {
      state.notes.splice(state.activeNote, 1) // here no matter what the first element is removed
      if (state.notes.length === 0) {
        state.activeNote.text = ''
        state.activeNote.favorite = false
      } else {
        state.activeNote = state.notes[state.notes.length - 1]
      }
    }
  },
  SET_ACTIVE_NOTE (state, note) {
    state.activeNote = note
  }
}

actions.js 是:

export const actions = {
  deleteNote: ({ commit }) => commit('DELETE_NOTE'),
  updateActiveNote: ({ commit }, note) => commit('SET_ACTIVE_NOTE', note),
}

吸气剂是:

const getters = {
  activeNote: state => state.activeNote,
  notes: state => state.notes,
}

我调用突变的组件是:

<template>
  <div id="toolbar">
    <i @click="deleteNote" class="glyphicon glyphicon-remove"></i>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'toolbar',
  computed: mapGetters([
    'activeNote'
  ]),
  methods: mapActions([
    'deleteNote',
  ])
}
</script>

【问题讨论】:

    标签: javascript arrays vue.js vue-component vuex


    【解决方案1】:

    您错误地使用了splice。 splice 的第一个参数是开始更改数组的 index。而不是

    state.notes.splice(state.activeNote, 1)
    

    你应该使用

    state.notes.splice(state.notes.indexOf(state.activeNote), 1)
    

    【讨论】:

    • 谢谢,这就是问题所在。
    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 2013-09-23
    • 2019-11-17
    • 2023-01-31
    • 2019-08-01
    • 2020-09-13
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多