案例一:博客系统
项目概述:
一个简单的博客系统,包括文章列表展示、文章详情查看、分类筛选、用户登录注册等功能。
技术栈:
- Vue.js
- Vue Router
- Vuex
- Axios
- Bootstrap
主要功能实现:
- 文章列表展示:
- 使用 Axios 从后端 API 获取文章列表数据。
- 在 Vue 组件中展示文章标题、摘要和发布日期等信息。
<template>
<div>
<h1>博客文章列表</h1>
<ul>
<li v-for="article in articles" :key="article.id">
<a :href="'/article/' + article.id">{
{ article.title }}</a>
<p>{
{ article.summary }}</p>
<small>{
{ article.publishedDate }}</small>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
articles: []
};
},
async created() {
try {
const response = await axios.get('/api/articles');
this.articles = response.data;
} catch (error) {
console.error('获取文章列表失败:', error);
}
}
};
</script>
- 文章详情查看:
- 通过 Vue Router 的动态路由参数获取文章 ID。
- 从后端获取特定文章的详细内容并展示。
<template>
<div>
<h1>{
{ article.title }}</h1>
<p>{
{ article.content }}</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
article: {}
};
},
async created() {
const articleId = this.$route.params.id;
try {
const response = await axios.get(`/api/articles/${articleId}`);
this.article = response.data;
} catch (error) {
console.error('获取文章详情失败:', error);
}
}
};
</script>
- 分类筛选:
- 展示不同的文章分类,用户点击分类可筛选出相应的文章列表。
<template>
<div>
<h1>博客文章列表</h1>
<ul>
<li v-for="category in categories" :key="category.id">
<a @click.prevent="filterArticlesByCategory(category.id)">{
{ category.name }}</a>
</li>
</ul>
<ul>
<li v-for="article in filteredArticles" :key="article.id">
<a :href="'/article/' + article.id">{
{ article.title }}</a>
<p>{
{ article.summary }}</p>
<small>{
{ article.publishedDate }}</small>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
articles: [],
categories: [],
filteredArticles: []
};
},
async created() {
try {
const articlesResponse = await axios.get('/api/articles');
this.articles = articlesResponse.data;
const categoriesResponse = await axios.get('/api/categories');
this.categories = categoriesResponse.data;
} catch (error) {
console.error('获取数据失败:', error);
}
},
methods: {
filterArticlesByCategory(categoryId) {
this.filteredArticles = this.articles.filter(article => article.categoryId === categoryId);
}
}
};
</script>
- 用户登录注册:
- 提供登录和注册表单,用户输入用户名、密码等信息进行操作。
- 使用 Axios 与后端进行交互,验证用户信息并处理登录注册流程。
<template>
<div>
<h2>登录</h2>
<form @submit.prevent="login">
<input type="text" v-model="username" placeholder="用户名">
<input type="password" v-model="password" placeholder="密码">
<button type="submit">登录</button>
</form>
<h2>注册</h2>
<form @submit.prevent="register">
<input type="text" v-model="newUsername" placeholder="用户名">
<input type="password" v-model="newPassword" placeholder="密码">
<button type="submit">注册</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: '',
newUsername: '',
newPassw