vue实现微博发布动态
Vue 实现微博发布动态功能
核心功能模块
- 动态输入框组件
- 图片/视频上传
- 发布按钮及交互逻辑
- 动态列表展示
基础组件结构
<template>
<div class="weibo-post">
<textarea v-model="content" placeholder="分享新鲜事..."></textarea>
<div class="media-preview">
<img v-for="(img, index) in images" :key="index" :src="img.preview">
<video v-if="video" :src="video.preview" controls></video>
</div>
<div class="action-bar">
<input type="file" @change="handleImageUpload" multiple accept="image/*">
<input type="file" @change="handleVideoUpload" accept="video/*">
<button @click="postWeibo" :disabled="!canPost">发布</button>
</div>
</div>
</template>
数据模型与状态管理
data() {
return {
content: '',
images: [],
video: null,
isPosting: false
}
},
computed: {
canPost() {
return (this.content.trim() || this.images.length || this.video)
&& !this.isPosting
}
}
媒体上传处理方法
methods: {
handleImageUpload(e) {
const files = Array.from(e.target.files)
files.forEach(file => {
const reader = new FileReader()
reader.onload = (event) => {
this.images.push({
file,
preview: event.target.result
})
}
reader.readAsDataURL(file)
})
},
handleVideoUpload(e) {
const file = e.target.files[0]
if (file) {
const reader = new FileReader()
reader.onload = (event) => {
this.video = {
file,
preview: event.target.result
}
}
reader.readAsDataURL(file)
}
}
}
发布功能实现
async postWeibo() {
this.isPosting = true
try {
const formData = new FormData()
formData.append('content', this.content)
this.images.forEach(img => {
formData.append('images', img.file)
})
if (this.video) {
formData.append('video', this.video.file)
}
const response = await axios.post('/api/weibo', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
this.$emit('posted', response.data)
this.resetForm()
} catch (error) {
console.error('发布失败:', error)
} finally {
this.isPosting = false
}
},
resetForm() {
this.content = ''
this.images = []
this.video = null
}
样式建议
.weibo-post {
border: 1px solid #e6e6e6;
padding: 15px;
border-radius: 4px;
}
textarea {
width: 100%;
min-height: 100px;
border: 1px solid #ddd;
padding: 10px;
resize: vertical;
}
.media-preview {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin: 10px 0;
}
.media-preview img {
max-width: 100px;
max-height: 100px;
object-fit: cover;
}
.action-bar {
display: flex;
gap: 10px;
align-items: center;
}
button {
padding: 8px 16px;
background-color: #ff8200;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
功能扩展建议
- 添加@用户提醒功能
- 实现话题标签自动识别
- 添加位置标记功能
- 实现草稿自动保存
- 添加字数限制提示
- 实现富文本编辑功能
注意事项
- 需要处理大文件上传的分片处理
- 考虑添加上传进度显示
- 实现客户端验证防止恶意内容
- 移动端需要优化文件选择体验
- 考虑添加发布后的回调处理
以上实现可以根据实际项目需求进行调整,核心逻辑包括内容输入、媒体上传和发布请求三个主要部分。







