vue实现微博发布动态
Vue 实现微博发布动态功能
数据绑定与表单设计
使用 Vue 的 v-model 实现表单双向绑定,创建动态内容输入框和图片上传组件。示例代码:
<template>
<div class="post-container">
<textarea v-model="postContent" placeholder="分享你的新鲜事..."></textarea>
<input type="file" @change="handleImageUpload" accept="image/*">
<button @click="submitPost" :disabled="!postContent">发布</button>
</div>
</template>
图片上传处理
通过 FileReader API 实现本地图片预览,建议限制图片大小并压缩:
methods: {
handleImageUpload(e) {
const file = e.target.files[0];
if (file.size > 5 * 1024 * 1024) {
alert('图片大小不能超过5MB');
return;
}
const reader = new FileReader();
reader.onload = (event) => {
this.previewImage = event.target.result;
};
reader.readAsDataURL(file);
}
}
动态发布逻辑
提交数据到后端前进行内容校验,包括敏感词过滤和空内容检查:
data() {
return {
postContent: '',
images: []
}
},
methods: {
async submitPost() {
if (!this.postContent.trim()) return;
const formData = new FormData();
formData.append('content', this.postContent);
this.images.forEach(img => {
formData.append('images', img.file);
});
try {
await axios.post('/api/posts', formData);
this.$emit('post-created');
this.resetForm();
} catch (error) {
console.error('发布失败:', error);
}
}
}
实时字数统计
添加输入内容长度监控,显示剩余字数:
<div class="counter">{{ 140 - postContent.length }}/140</div>
<style>
.counter {
color: var(--text-secondary);
text-align: right;
font-size: 0.8em;
}
</style>
优化用户体验
-
添加加载状态防止重复提交
data() { return { isLoading: false } }, methods: { async submitPost() { if (this.isLoading) return; this.isLoading = true; // ...提交逻辑 this.isLoading = false; } } -
实现@用户提及功能 使用正则表达式匹配@符号,建议结合第三方库如
vue-mention实现智能提示。
移动端适配要点
-
调整输入框高度适应移动键盘
textarea { min-height: 120px; resize: none; } -
添加触摸反馈效果
button:active { transform: scale(0.98); }
安全注意事项
-
前端做XSS过滤
import DOMPurify from 'dompurify'; this.postContent = DOMPurify.sanitize(this.postContent); -
敏感词检测(需结合后端)
const bannedWords = ['敏感词1', '敏感词2']; const hasBannedWord = bannedWords.some(word => this.postContent.includes(word) ); if (hasBannedWord) { alert('内容包含不合适词汇'); return; }







