我正在使用Laravel 5.5,Vue 2和Vuex创建系统评论。 我无法发表评论。我进入我的控制台,有两个错误:
TypeError:this.addComment不是函数
错误:请求失败,状态码为422
这是我的代码:
export const addComment = function ({dispatch}, comment) {
return axios.post('/comments', comment).then((response) => {
dispatch('ADD_COMMENT', response.data)
})
};
actions.js代码
{{1}}
我的所有路线,控制器和突变都经过测试并且运行良好。
答案 0 :(得分:1)
只要全局注册store
,您就无需将操作导入组件。所以你只需要像这样调用addComment
:
this.$store.dispatch('addComment', {
commentable_id: this.id,
commentable_type: this.model,
content: this.content,
reply: this.reply
})
另外,将addComment
放在computed
中没有意义,因此您必须将其删除。
在您的addComment操作中,我认为它被称为commit
而不是dispatch
:
export const addComment = function ({commit}, comment) {
return axios.post('/comments', comment).then((response) => {
commit('ADD_COMMENT', response.data)
})
}
答案 1 :(得分:0)
我的Store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export const state = {
comments: []
};
export const mutations = {
ADD_COMMENTS (state, comments) {
state.comments.push(...comments)
},
ADD_COMMENT (state, comment) {
if (comment.reply) {
let c = state.comments.find((c) => c.id === comment.reply);
if (c.replies === undefined) {
c.replies = []
}
c.replies.push(comment)
} else {
state.comments.push(comment)
},
DELETE_COMMENT () {...}
};
let store = new Vuex.Store({
state: state,
mutations: mutations
});
export default store;
我的Form.vue组件:
import { addComment } from '../../store/actions'
import { mapActions } from 'vuex'
export default {
vuex: {
actions: { addComment }
},
data () {
return {
content: '',
loading: false
}
},
props: {
id: Number,
model: String,
reply: {
type: Number,
default: 0
}
},
methods: {
sendComment: function () {
this.loading = true;
this.$store.dispatch('addComment', {
commentable_id: this.id,
commentable_type: this.model,
content: this.content,
reply: this.reply
}).catch((error) => {
this.error = error.response.data
}).then(() => {
this.loading = false
})
}
}
}