【发布时间】:2022-01-21 20:57:00
【问题描述】:
首先,我使用的是 vuex 和 axios。
- 存储:commentService.js
- 组件:
- CommentBox.vue(顶级组件)
- CommentEnter.vue(子组件)
这是我写的代码的逻辑。
在名为commentService.js 的商店中,有一个名为commentUpdate 的突变。
还有叫postComment和getComment的动作。
此时,在名为CommentBox 的组件中调度getComment 和async created()。
然后,在getComment 中,commentUpdate 被提交并执行。
CommentUpdate 创建一个由getComment 查询的 cmets 数组,并将它们存储在名为 commentList 的状态中。
然后我会得到一个带有“computed”的commentList。
CommentEnter,子组件,使用CommentBox中注册为复合的commentList作为prop。
下面的代码是commentService.js。
import axios from 'axios'
export default {
namespaced: true,
state: () => ({
comment:'',
commentList: []
}),
mutations: {
commentUpdate(state, payload) {
Object.keys(payload).forEach(key => {
state[key] = payload[key]
})
}
},
actions: {
postComment(state, payload) {
const {id} = payload
axios.post(`http://??.???.???.???:????/api/books/${id}/comments`, {
comment: this.state.comment,
starRate: this.state.starRate
}, {
headers: {
Authorization: `Bearer ` + localStorage.getItem('user-token')
}
})
.then((res) => {
console.log(res)
this.state.comment = ''
this.state.starRate = ''
)
.catch((err) => {
alert('댓글은 한 책당 한 번만 작성할 수 있습니다.')
console.log(err)
this.state.comment = ''
this.state.starRate = ''
})
},
async getComment({commit}, payload) {
const {id} = payload
axios.get(`http://??.???.???.???:????/api/books/${id}/comments`)
.then((res) => {
console.log(res)
const { comment } = res.data.commentMap
commit('commentUpdate', {
commentList: comment
})
})
.catch((err) => {
console.log(err)
commit('commentUpdate', {
commentList: {}
})
})
}
}
}
下面的代码是 CommentBox.vue
computed: {
commentList() {
return this.$store.state.commentService.commentList
}
},
methods: {
async newComment() {
if(this.$store.state.loginService.UserInfoObj.id === '') {
alert('로그인 후 이용할 수 있습니다.')
return
}
this.$store.dispatch('commentService/postComment', {
id: this.$route.params.id,
comment: this.$store.state.comment,
starRate: this.$store.state.starRate
})
}
},
async created() {
this.$store.dispatch('commentService/getComment', {
id: this.$route.params.id
})
}
下面的代码是 CommentEnter.vue
created() {
this.userComment = this.comment
},
props: {
comment: {
type: Object,
default: () => {}
}
},
我征求了很多建议。
在axios post请求成功后,有很多cmets请求axios get请求。
其实我在axios post的.then()内请求了一个axios get,network tab确认get请求在post请求之后正常发生。
但是当我注册一个新评论时仍然没有立即看到。
我只能在刷新时看到新的 cmets。
如何让新评论在注册后立即出现在屏幕上?
【问题讨论】:
-
尝试删除异步/等待对。
-
哪些异步/等待对?全部?
-
是的。我建议使用基于 promise 或 async/await 语法。混合它们很笨拙。
-
好的,那么注册完cmets之后,不刷新怎么才能看到注册的cmets呢?
-
你能把新代码贴出来让我们看看吗?