在尝试编辑项目时,我无法弄清楚我做错了什么。我已经设法在组件状态下使用firebase使其工作,但我无法使用vuex工作。
Firebase Flow:
尝试修改时出错:
这是我的代码。我已经注释掉了在我的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>
答案 0 :(得分:1)
简而言之,rootFolder->
js->
something.js
css->
style.css
index.html
参数(第3个)是payload
,因为......
Mutations的功能签名始终采用undefined
的形式,这意味着数据必须采用(state, payload)
形式,如下所示:
Object
然后在你的函数声明中:
this.EDIT_ITEM({
key: index,
value: payload
})
我更改了有效负载变量名称只是为了区分清楚,希望它不会增加混乱。