vue实现新闻编辑页
Vue 新闻编辑页实现步骤
基础项目搭建
使用 Vue CLI 或 Vite 创建项目,安装必要依赖:
npm install vue-router axios quill
路由配置
在 router/index.js 中配置编辑页路由:
{
path: '/news/edit/:id?',
name: 'NewsEdit',
component: () => import('../views/NewsEdit.vue')
}
富文本编辑器集成
使用 Quill 实现富文本编辑功能:
<template>
<div class="editor-container">
<div ref="editor" style="height: 400px"></div>
</div>
</template>
<script>
import Quill from 'quill'
import 'quill/dist/quill.snow.css'
export default {
mounted() {
this.quill = new Quill(this.$refs.editor, {
theme: 'snow',
modules: {
toolbar: [
['bold', 'italic', 'underline'],
[{ 'header': [1, 2, 3] }],
['link', 'image']
]
}
})
}
}
</script>
表单数据绑定
实现新闻数据的双向绑定:

<template>
<form @submit.prevent="handleSubmit">
<input v-model="news.title" placeholder="标题">
<input v-model="news.author" placeholder="作者">
<select v-model="news.category">
<option v-for="cat in categories" :value="cat">{{ cat }}</option>
</select>
</form>
</template>
<script>
export default {
data() {
return {
news: {
title: '',
content: '',
author: '',
category: ''
},
categories: ['政治', '经济', '科技', '体育']
}
}
}
</script>
图片上传处理
实现图片上传功能:
methods: {
uploadImage() {
const input = document.createElement('input')
input.type = 'file'
input.accept = 'image/*'
input.onchange = async () => {
const formData = new FormData()
formData.append('image', input.files[0])
try {
const res = await axios.post('/api/upload', formData)
const range = this.quill.getSelection()
this.quill.insertEmbed(range.index, 'image', res.data.url)
} catch (error) {
console.error(error)
}
}
input.click()
}
}
数据提交处理
实现表单提交逻辑:
methods: {
async handleSubmit() {
this.news.content = this.quill.root.innerHTML
try {
if (this.$route.params.id) {
await axios.put(`/api/news/${this.$route.params.id}`, this.news)
} else {
await axios.post('/api/news', this.news)
}
this.$router.push('/news/list')
} catch (error) {
console.error('保存失败', error)
}
}
}
初始化数据加载
编辑时加载现有数据:

async created() {
if (this.$route.params.id) {
const res = await axios.get(`/api/news/${this.$route.params.id}`)
this.news = res.data
this.quill.clipboard.dangerouslyPasteHTML(this.news.content)
}
}
样式优化
添加基本样式:
.editor-container {
border: 1px solid #ddd;
border-radius: 4px;
}
.ql-toolbar {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
background-color: #f5f5f5;
}
.ql-container {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
表单验证
添加基础验证逻辑:
methods: {
validateForm() {
if (!this.news.title.trim()) {
this.$message.error('请输入标题')
return false
}
if (!this.news.content.trim()) {
this.$message.error('请输入内容')
return false
}
return true
},
async handleSubmit() {
if (!this.validateForm()) return
// 提交逻辑...
}
}
响应式布局
添加响应式设计:
@media (max-width: 768px) {
.editor-container {
margin: 0 10px;
}
.ql-toolbar .ql-formats {
margin-right: 5px;
}
}






