diff --git a/3.vue/5.server-render/nuxt-realworld/hooks/useComment.ts b/3.vue/5.server-render/nuxt-realworld/hooks/useComment.ts new file mode 100644 index 0000000..2fb9190 --- /dev/null +++ b/3.vue/5.server-render/nuxt-realworld/hooks/useComment.ts @@ -0,0 +1,31 @@ +import { + getCommentsFromArticle, + type ArticleComment, + postComment, +} from "~/service/comment" + +function useComment(slug: string) { + const comments = ref([]) + const comment = ref("") + + const getComment = async (watching = false) => { + const { data } = await getCommentsFromArticle(slug) + + comments.value = data.value?.comments || [] + watching && + watch(data, (newData) => { + comments.value = newData?.comments || [] + }) + } + + const handlePostComment = async (body: string) => { + if (!body) return + await postComment(slug, body.trim()) + getComment() + comment.value = "" + } + + return { comments, comment, getComment, handlePostComment } +} + +export default useComment diff --git a/3.vue/5.server-render/nuxt-realworld/pages/article/components/ArticleComments.vue b/3.vue/5.server-render/nuxt-realworld/pages/article/components/ArticleComments.vue index 897a96d..3aa6298 100644 --- a/3.vue/5.server-render/nuxt-realworld/pages/article/components/ArticleComments.vue +++ b/3.vue/5.server-render/nuxt-realworld/pages/article/components/ArticleComments.vue @@ -1,7 +1,12 @@