gpt4 book ai didi

javascript - Vuex 仅删除第一个元素

转载 作者:行者123 更新时间:2023-12-01 03:16:24 27 4
gpt4 key购买 nike

我有以下设置,尝试使用 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),
}

setter/getter 是:

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>

最佳答案

您正在使用splice错误地。 splice 的第一个参数是开始更改数组的索引。而不是

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

你应该使用

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

关于javascript - Vuex 仅删除第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45509946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com