vue实现问答社区
Vue 实现问答社区的核心步骤
技术栈选择
- Vue 3(Composition API)
- Vue Router 实现前端路由
- Pinia/Vuex 状态管理
- Axios 处理 HTTP 请求
- Element Plus/Vant UI 组件库
项目结构设计
src/
├── assets/
├── components/
│ ├── QuestionList.vue
│ ├── AnswerEditor.vue
│ └── UserProfile.vue
├── views/
│ ├── Home.vue
│ ├── QuestionDetail.vue
│ └── AskQuestion.vue
├── store/
├── router/
└── api/
核心功能实现
用户认证模块
// store/auth.js
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null,
token: localStorage.getItem('token') || ''
}),
actions: {
async login(credentials) {
const res = await axios.post('/api/login', credentials)
this.token = res.data.token
localStorage.setItem('token', this.token)
}
}
})
问题列表展示
<!-- QuestionList.vue -->
<template>
<div v-for="q in questions" :key="q.id">
<h3 @click="router.push(`/question/${q.id}`)">{{ q.title }}</h3>
<p>{{ q.content }}</p>
</div>
</template>
<script setup>
const { data: questions } = await useFetch('/api/questions')
</script>
问答交互功能
问题详情页
// router/index.js
{
path: '/question/:id',
component: () => import('@/views/QuestionDetail.vue'),
props: true
}
回答编辑器
<!-- AnswerEditor.vue -->
<template>
<textarea v-model="content"></textarea>
<button @click="submitAnswer">提交回答</button>
</template>
<script setup>
const props = defineProps(['questionId'])
const content = ref('')
const submitAnswer = async () => {
await axios.post(`/api/question/${props.questionId}/answers`, { content })
}
</script>
数据状态管理
问题状态管理
// store/questions.js
export const useQuestionStore = defineStore('questions', {
state: () => ({
questions: [],
currentQuestion: null
}),
actions: {
async fetchQuestions() {
this.questions = await axios.get('/api/questions')
},
async fetchQuestion(id) {
this.currentQuestion = await axios.get(`/api/questions/${id}`)
}
}
})
性能优化方案
列表虚拟滚动
<template>
<RecycleScroller
:items="questions"
:item-size="100"
key-field="id"
>
<template v-slot="{ item }">
<QuestionItem :question="item" />
</template>
</RecycleScroller>
</template>
API 请求封装
// api/question.js
export const getQuestions = (params) => {
return axios.get('/api/questions', { params })
}
export const createQuestion = (data) => {
return axios.post('/api/questions', data)
}
部署注意事项
-
配置生产环境 API 基础 URL
VUE_APP_API_URL=https://api.yourdomain.com -
启用路由 history 模式需要服务器配置
location / { try_files $uri $uri/ /index.html; } -
静态资源打包优化
// vite.config.js build: { rollupOptions: { output: { manualChunks: { 'vendor': ['vue', 'vue-router', 'pinia'] } } } }




