Vuex只删除第一个元素

时间:2017-08-04 14:56:59

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

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

mutation.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>

1 个答案:

答案 0 :(得分:2)

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

/

你应该使用

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