编写一个模拟数据的完整博客网站
时间: 2024-02-23 16:58:33 浏览: 18
以下是一个使用Vue.js和模拟数据实现的简单博客网站:
前端代码:
```
<template>
<div>
<h1>My Blog</h1>
<div v-if="!user">
<h3>Please login to view your posts.</h3>
<button @click="login">Login</button>
</div>
<div v-else>
<form @submit.prevent="addPost">
<input v-model="newPost.title" placeholder="Title">
<textarea v-model="newPost.content" placeholder="Write something..."></textarea>
<button type="submit">Add Post</button>
</form>
<ul>
<li v-for="post in posts" :key="post.id">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<button @click="deletePost(post.id)">Delete</button>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
user: null,
newPost: {
title: "",
content: "",
},
posts: [],
};
},
mounted() {
this.user = true; // 模拟已登录状态
this.getPosts();
},
methods: {
login() {
this.user = true; // 模拟已登录状态
this.getPosts();
},
addPost() {
if (!this.newPost.title.trim() || !this.newPost.content.trim()) return;
const newId = this.posts.length + 1;
this.posts.push({
id: newId,
title: this.newPost.title,
content: this.newPost.content,
});
this.newPost.title = "";
this.newPost.content = "";
},
getPosts() {
// 模拟异步请求数据
setTimeout(() => {
this.posts = [
{
id: 1,
title: "First Post",
content: "This is my first blog post.",
},
{
id: 2,
title: "Second Post",
content: "This is my second blog post.",
},
{
id: 3,
title: "Third Post",
content: "This is my third blog post.",
},
];
}, 1000);
},
deletePost(postId) {
this.posts = this.posts.filter((post) => post.id !== postId);
},
},
};
</script>
```
这个博客网站的前端使用Vue.js实现,包括登录、添加、查看和删除文章等功能。它使用了模拟数据代替后端服务,实现了数据的存储和读取。
需要注意的是,由于这个博客网站使用了模拟数据,因此在实际应用中需要将数据的存储和读取改为使用后端服务。