vue实现新闻浏览编辑
Vue 实现新闻浏览编辑功能
项目结构搭建
使用 Vue CLI 快速初始化项目,安装必要依赖如 vue-router 和 axios。创建以下核心目录:
src/views/存放新闻列表和编辑页面组件src/components/存放可复用的新闻卡片、编辑器等子组件src/api/封装新闻数据的 API 请求
vue create news-app
cd news-app
npm install axios vue-router
新闻列表展示
创建 NewsList.vue 组件,通过 v-for 渲染新闻条目。使用 axios 从后端 API 获取数据:
<template>
<div class="news-list">
<NewsCard
v-for="item in newsList"
:key="item.id"
:title="item.title"
:content="item.content"
@edit="handleEdit(item.id)"
/>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
newsList: []
}
},
async created() {
const res = await axios.get('/api/news')
this.newsList = res.data
}
}
</script>
富文本编辑器集成
推荐使用 quill 或 tinymce-vue 实现编辑功能。以 vue-quill-editor 为例:
npm install vue-quill-editor
在 NewsEditor.vue 中配置编辑器:
<template>
<div class="editor-wrapper">
<quill-editor
v-model="content"
:options="editorOptions"
/>
<button @click="submit">保存</button>
</div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
export default {
components: { quillEditor },
data() {
return {
content: '',
editorOptions: {
modules: {
toolbar: [
['bold', 'italic'],
['link', 'image']
]
}
}
}
}
}
</script>
路由配置
在 router/index.js 中设置页面跳转逻辑:
import { createRouter } from 'vue-router'
import NewsList from '../views/NewsList.vue'
import NewsEditor from '../views/NewsEditor.vue'
const routes = [
{ path: '/', component: NewsList },
{ path: '/edit/:id', component: NewsEditor }
]
const router = createRouter({
history: createWebHistory(),
routes
})
状态管理优化
对于复杂场景可使用 Vuex 管理新闻数据状态:
// store/modules/news.js
export default {
state: {
currentNews: null
},
mutations: {
SET_CURRENT_NEWS(state, news) {
state.currentNews = news
}
}
}
表单验证
使用 vee-validate 对编辑表单进行校验:
<ValidationObserver v-slot="{ handleSubmit }">
<form @submit.prevent="handleSubmit(submit)">
<ValidationProvider rules="required" v-slot="{ errors }">
<input v-model="title" />
<span>{{ errors[0] }}</span>
</ValidationProvider>
</form>
</ValidationObserver>
响应式布局
通过 CSS Grid 或 Flexbox 实现自适应布局:
.news-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
}
数据持久化
编辑完成后通过 API 提交到后端:
methods: {
async submit() {
await axios.patch(`/api/news/${this.id}`, {
title: this.title,
content: this.content
})
this.$router.push('/')
}
}
权限控制
通过路由守卫实现编辑权限验证:
router.beforeEach((to, from, next) => {
if (to.path.includes('/edit') && !isAuthenticated()) {
next('/login')
} else {
next()
}
})






