我无法弄清楚在尝试编辑项目时我做错了什么。我已经设法在组件状态中使用 firebase 使其工作,但我无法使用 vuex 使其工作。
Firebase 流程:
尝试编辑时出错:
这是我的代码。我注释掉了在我的 editItem
方法中工作的代码,并包含了我商店中不起作用的突变函数。
Store.js
import Vue from 'vue'
import Vuex from 'vuex'
import database from './firebase'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
items: []
},
mutations: {
RENDER_ITEMS(state) {
database.ref('items').on('value', snapshot => {
state.items = snapshot.val()
})
},
ADD_ITEM(state, payload) {
state.items = payload
database.ref('items').push(payload)
},
REMOVE_ITEM(index) {
database.ref(`items/${index}`).remove()
},
EDIT_ITEM(state, index, payload) {
database.ref(`items/${index}`).set(payload)
}
},
// actions: {
// }
})
Main.vue
<template>
<div class="hello">
<input type="text" placeholder="name" v-model="name">
<input type="text" placeholder="age" v-model="age">
<input type="text" placeholder="status" v-model="status">
<input type="submit" @click="addItem" />
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }}
{{ item.age }}
{{ item.status }}
<button @click="removeItem(index)">Remove</button>
<button @click="editItem(index, item)">Edit</button>
</li>
</ul>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import database from '../firebase' // TEST REASONS
import uuid from 'uuid'
export default {
name: 'HelloWorld',
created() {
this.RENDER_ITEMS(this.items)
},
data() {
return {
name: '',
age: '',
status: '',
id: uuid(),
}
},
computed: {
...mapState([
'items'
])
},
methods: {
...mapMutations([
'RENDER_ITEMS',
'ADD_ITEM',
'REMOVE_ITEM',
'EDIT_ITEM'
]),
addItem() {
const item = {
name: this.name,
age: this.age,
status: this.status,
id: this.id
}
this.ADD_ITEM(item)
this.name = ''
this.age = ''
this.status = ''
},
removeItem(index) {
this.REMOVE_ITEM(index)
},
editItem(index, item) {
const payload = {
name: item.name,
age: item.age,
status: item.status
}
this.EDIT_ITEM(index, payload) // THIS DOESN'T
// database.ref(`items/${index}`).set(payload) THIS WORKS //
}
}
}
</script>
最佳答案
简而言之,第三个参数payload
是undefined
,因为...
Mutations的函数签名始终采用(state, payload)
的形式,这意味着数据必须以Object
形式出现,如下所示:
this.EDIT_ITEM({
key: index,
value: payload
})
然后在你的函数声明上:
EDIT_ITEM(state, payload) {
database.ref(`items/${payload.key}`).set(payload.value)
}
我更改了负载变量名称只是为了清楚区分,希望它不会增加困惑。
关于javascript - 使用 Vuex 和 Firebase 编辑项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50454814/