Два вопроса
export default {
//....
computed:{
items: {
return this.$store.getters.Items
}
},
methods :{
removeItem(id) {
this.$store.dispatch('removeItem', id)
}
}
}
<template>
<div >
<ul v-for = "item in items" :key = "item.id">
<li> {{item.name}} <button @click = "removeItem(item.id)">X</button></li>
</ul>
</div>
</template>
Вот пример моего файла store.js
import db from 'firebase/init.js'
state: {
items: []
},
mutations: {
SETMENUITEMS(state, items) {
state.items = items
}
REMOVEITEM(state, id) {
state.menuItems.filter(item => {
return item.id != id
})
}
},
actions: {
//I dispatch this action in the created life hook of my root .vue app component to have the items loaded upon initilizing the app
fetchMenuItems({commit}){
const menuItems = []
db.collection('myCollection').get()
.then(snapshot => {
snapshot.forEach(doc => {
let item = doc.data()
item.id = doc.id;
menuItems.push(item)
})
commit('SETMENUITEMS', menuItems)
})
.catch(err => console.info(err))
},
removeItem({commit}, id){
db.collection('myCollection').doc(id).delete()
.then(() => {
//at this point the item is already deleted from the database but since the ap didn't reload the item is still showing
commit('REMOVEITEM', id)
})
.catch(err => console.info(err.message)
}
},
getters: {
Items: state => state.items
}
пожалуйста, оставьте комментарий ниже для дальнейших разъяснений о желаемом поведении, извините за длинный вопрос и заранее благодарим.
Постараюсь ответить на первый вопрос.
вы совершаете фиксацию в магазине, поскольку обещание выполнено. Я думаю, что обещание выполняется только один раз.
Попробуйте прикрепить свой код непосредственно к коллекции с помощью onSnapshot, чтобы вы могли передать наблюдателю непосредственно наблюдаемую коллекцию:
...
actions: {
//I dispatch this action in the created life hook of my root .vue app component to have the items loaded upon initilizing the app
fetchMenuItems({commit}){
const menuItems = []
db.collection('myCollection').onSnapshot(snapshot => {
snapshot.forEach(doc => {
let item = doc.data()
item.id = doc.id;
menuItems.push(item)
})
commit('SETMENUITEMS', menuItems)
})
.catch(err => console.info(err))
},
removeItem({commit}, id){
db.collection('myCollection').doc(id).delete()
.then(() => {
//at this point the item is already deleted from the database but since the ap didn't reload the item is still showing
commit('REMOVEITEM', id)
})
.catch(err => console.info(err.message)
}
},
...
об удалении всей коллекции не рекомендуется использовать веб-клиент, как вы можете видеть в документе: Удалить данные