vue发布动态功能实现
实现Vue动态发布功能
前端实现
使用Vue.js构建动态发布表单,包含文本输入和图片上传功能
<template>
<div>
<textarea v-model="content" placeholder="分享你的想法..."></textarea>
<input type="file" @change="handleFileUpload" accept="image/*">
<button @click="postDynamic">发布</button>
</div>
</template>
<script>
export default {
data() {
return {
content: '',
images: []
}
},
methods: {
handleFileUpload(e) {
this.images = Array.from(e.target.files)
},
async postDynamic() {
const formData = new FormData()
formData.append('content', this.content)
this.images.forEach(img => {
formData.append('images', img)
})
try {
await axios.post('/api/dynamics', formData)
this.$emit('posted')
this.content = ''
this.images = []
} catch (error) {
console.error(error)
}
}
}
}
</script>
后端API设计
Node.js Express示例处理动态发布请求

const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
router.post('/dynamics', upload.array('images'), async (req, res) => {
try {
const { content } = req.body
const images = req.files.map(file => file.path)
const newDynamic = new Dynamic({
content,
images,
author: req.user.id
})
await newDynamic.save()
res.status(201).json(newDynamic)
} catch (error) {
res.status(500).json({ error: error.message })
}
})
数据库模型
MongoDB动态数据模型设计

const mongoose = require('mongoose')
const dynamicSchema = new mongoose.Schema({
content: String,
images: [String],
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
likes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}],
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Dynamic', dynamicSchema)
图片处理
使用Sharp库进行图片优化处理
const sharp = require('sharp')
async function processImage(file) {
const filename = `${Date.now()}.webp`
await sharp(file.path)
.resize(800, 800, { fit: 'inside' })
.webp({ quality: 80 })
.toFile(`public/uploads/${filename}`)
return `/uploads/${filename}`
}
前端展示动态列表
Vue组件展示动态列表
<template>
<div v-for="dynamic in dynamics" :key="dynamic._id">
<p>{{ dynamic.content }}</p>
<div v-for="img in dynamic.images" :key="img">
<img :src="img" alt="动态图片">
</div>
<button @click="likeDynamic(dynamic._id)">点赞</button>
</div>
</template>
<script>
export default {
props: ['dynamics'],
methods: {
async likeDynamic(id) {
await axios.post(`/api/dynamics/${id}/like`)
this.$emit('liked')
}
}
}
</script>






