vue实现发帖
使用 Vue 实现发帖功能
前端实现
创建发帖表单组件,包含标题和内容输入框,以及提交按钮。使用 v-model 绑定表单数据。
<template>
<div>
<input v-model="post.title" placeholder="标题" />
<textarea v-model="post.content" placeholder="内容"></textarea>
<button @click="submitPost">发布</button>
</div>
</template>
<script>
export default {
data() {
return {
post: {
title: '',
content: ''
}
}
},
methods: {
submitPost() {
this.$emit('submit', this.post)
this.post.title = ''
this.post.content = ''
}
}
}
</script>
后端 API 调用
在父组件中处理发帖逻辑,调用 API 发送数据到后端。
methods: {
async handleSubmit(post) {
try {
const response = await axios.post('/api/posts', post)
console.log('发帖成功', response.data)
} catch (error) {
console.error('发帖失败', error)
}
}
}
表单验证
添加简单的表单验证,确保标题和内容不为空。
methods: {
submitPost() {
if (!this.post.title.trim() || !this.post.content.trim()) {
alert('标题和内容不能为空')
return
}
this.$emit('submit', this.post)
}
}
状态管理
使用 Vuex 管理帖子列表状态,在发帖成功后更新全局状态。
// store.js
mutations: {
ADD_POST(state, post) {
state.posts.unshift(post)
}
}
// 组件中
methods: {
async handleSubmit(post) {
try {
const response = await axios.post('/api/posts', post)
this.$store.commit('ADD_POST', response.data)
} catch (error) {
console.error(error)
}
}
}
路由跳转
发帖成功后跳转到帖子列表页。
methods: {
async handleSubmit(post) {
try {
await axios.post('/api/posts', post)
this.$router.push('/posts')
} catch (error) {
console.error(error)
}
}
}






