vue实现发表
Vue实现发表功能
要实现一个发表功能,通常需要前端Vue.js与后端API的配合。以下是实现步骤:
前端Vue.js部分
- 创建表单组件
<template> <div> <textarea v-model="content" placeholder="输入内容"></textarea> <button @click="submitPost">发表</button> </div> </template>
- 在父组件中使用
<template> <div> <PostForm @post-created="handleNewPost" /> <PostList :posts="posts" /> </div> </template>
export default { components: { PostForm, PostList }, data() { return { posts: [] } }, methods: { handleNewPost(post) { this.posts.unshift(post) } } }
```后端API部分
- 创建Express.js路由
const express = require('express') const router = express.Router() const Post = require('../models/Post')
router.post('/posts', async (req, res) => { try { const { content } = req.body const newPost = new Post({ content }) await newPost.save() res.status(201).json(newPost) } catch (error) { res.status(500).json({ error: '发表失败' }) } })

module.exports = router
2. MongoDB模型
```javascript
const mongoose = require('mongoose')
const postSchema = new mongoose.Schema({
content: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Post', postSchema)
完整实现流程
- 前端Vue组件收集用户输入内容
- 点击发表按钮触发submitPost方法
- 使用axios向后端API发送POST请求
- 后端接收请求并保存到数据库
- 返回新创建的帖子数据
- 前端接收响应并更新UI显示
额外功能扩展

-
添加表单验证
methods: { validateForm() { return this.content.trim().length > 0 }, async submitPost() { if (!this.validateForm()) { alert('内容不能为空') return } // 其余代码... } } -
添加加载状态
data() { return { content: '', isLoading: false } }, methods: { async submitPost() { this.isLoading = true try { // 发表代码... } finally { this.isLoading = false } } } -
添加图片上传
<template> <input type="file" @change="handleFileUpload"> </template>
await axios.post('/api/posts', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
} }
```





