当前位置:首页 > VUE

vue实现发表博客

2026-02-17 16:59:26VUE

Vue 实现发表博客功能

前端部分(Vue.js)

安装必要依赖(如需要)

npm install axios vue-router

创建博客发布组件(BlogEditor.vue)

<template>
  <div class="blog-editor">
    <h3>发布新博客</h3>
    <form @submit.prevent="submitBlog">
      <div class="form-group">
        <label>标题</label>
        <input v-model="blog.title" type="text" required>
      </div>
      <div class="form-group">
        <label>内容</label>
        <textarea v-model="blog.content" rows="10" required></textarea>
      </div>
      <button type="submit">发布</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      blog: {
        title: '',
        content: ''
      }
    }
  },
  methods: {
    async submitBlog() {
      try {
        const response = await axios.post('/api/blogs', this.blog);
        alert('博客发布成功');
        this.$router.push('/blogs');
      } catch (error) {
        console.error('发布失败:', error);
      }
    }
  }
}
</script>

配置路由(router/index.js)

import { createRouter, createWebHistory } from 'vue-router'
import BlogEditor from '../components/BlogEditor.vue'

const routes = [
  {
    path: '/blogs/new',
    component: BlogEditor
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

后端部分(Node.js示例)

安装必要依赖

npm install express body-parser cors

创建简单API服务(server.js)

vue实现发表博客

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(bodyParser.json());
app.use(cors());

let blogs = [];

app.post('/api/blogs', (req, res) => {
  const newBlog = {
    id: Date.now(),
    title: req.body.title,
    content: req.body.content,
    createdAt: new Date()
  };
  blogs.push(newBlog);
  res.status(201).json(newBlog);
});

app.get('/api/blogs', (req, res) => {
  res.json(blogs);
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

数据库集成(可选MongoDB)

安装Mongoose

npm install mongoose

修改server.js连接数据库

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/blogDB', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const blogSchema = new mongoose.Schema({
  title: String,
  content: String,
  createdAt: { type: Date, default: Date.now }
});

const Blog = mongoose.model('Blog', blogSchema);

app.post('/api/blogs', async (req, res) => {
  try {
    const blog = new Blog(req.body);
    await blog.save();
    res.status(201).json(blog);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

富文本编辑器集成(如需要)

安装vue-quill编辑器

vue实现发表博客

npm install vue-quill@beta @vueup/vue-quill@beta

修改BlogEditor.vue

<template>
  <div>
    <QuillEditor v-model:content="blog.content" contentType="html" />
  </div>
</template>

<script>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';

export default {
  components: { QuillEditor }
}
</script>

用户认证(可选)

添加登录验证中间件

// server.js
const authenticate = (req, res, next) => {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: '未授权' });
  }
  next();
};

app.post('/api/blogs', authenticate, async (req, res) => {
  // 原有代码
});

前端添加Authorization头

// BlogEditor.vue
axios.post('/api/blogs', this.blog, {
  headers: {
    'Authorization': `Bearer ${localStorage.getItem('token')}`
  }
})

标签: 博客vue
分享给朋友:

相关文章

vue实现关键词轮播

vue实现关键词轮播

Vue 实现关键词轮播 基础实现方案 使用 Vue 的 v-for 和 setInterval 实现基础轮播效果: <template> <div class="keyword…

vue实现图集

vue实现图集

Vue 实现图集的方法 在 Vue 中实现图集功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用第三方库(如 vue-image-lightbox) 安装 vue-image-ligh…

vue实现过程

vue实现过程

Vue 的实现过程 Vue 的实现过程可以分为多个核心模块,包括响应式系统、虚拟 DOM、模板编译等。以下是 Vue 的主要实现过程分析。 响应式系统 Vue 的响应式系统基于 Object.def…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue实现webapp

vue实现webapp

Vue 实现 WebApp 的基本步骤 环境准备 确保已安装 Node.js 和 npm/yarn。通过 Vue CLI 或 Vite 创建项目: npm install -g @vue/cli v…

vue源码实现

vue源码实现

Vue 源码实现解析 Vue.js 的核心实现可以分为响应式系统、虚拟 DOM、模板编译、组件化等几个关键部分。以下是对这些核心机制的详细解析。 响应式系统 Vue 的响应式系统基于 Object.…