vue实现秀米
Vue 实现类似秀米的富文本编辑器
使用 Vue 实现类似秀米的富文本编辑器需要结合富文本编辑库和自定义组件。以下是实现方案:
方案一:基于 Quill 的扩展 安装 Quill 和相关插件:
npm install quill vue-quill-editor
创建自定义编辑器组件:
<template>
<div class="editor-container">
<quill-editor
v-model="content"
:options="editorOptions"
@change="onEditorChange"
/>
<div class="toolbar">
<button @click="insertTemplate('header')">插入标题</button>
<button @click="insertTemplate('image')">插入图片</button>
</div>
</div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
export default {
components: { quillEditor },
data() {
return {
content: '',
editorOptions: {
modules: {
toolbar: [
['bold', 'italic', 'underline'],
['image', 'video']
]
}
}
}
},
methods: {
onEditorChange({ html }) {
console.log(html)
},
insertTemplate(type) {
if(type === 'header') {
this.content += '<h1>标题文字</h1>'
}
}
}
}
</script>
方案二:使用 Tiptap 编辑器 Tiptap 是基于 ProseMirror 的现代编辑器:
npm install @tiptap/vue-2 @tiptap/starter-kit
实现组件:
<template>
<editor-content :editor="editor" />
</template>
<script>
import { Editor, EditorContent } from '@tiptap/vue-2'
import StarterKit from '@tiptap/starter-kit'
export default {
components: { EditorContent },
data() {
return {
editor: null
}
},
mounted() {
this.editor = new Editor({
content: '<p>初始内容</p>',
extensions: [
StarterKit
],
onUpdate: ({ editor }) => {
console.log(editor.getHTML())
}
})
}
}
</script>
实现秀米特色功能
模板系统 创建可复用的模板组件:
<template>
<div class="template-gallery">
<div
v-for="(temp, index) in templates"
:key="index"
@click="applyTemplate(temp)"
>
<img :src="temp.preview">
</div>
</div>
</template>
<script>
export default {
data() {
return {
templates: [
{ id: 1, preview: 'header.png', html: '<div class="xiumi-header">...</div>' }
]
}
},
methods: {
applyTemplate(template) {
this.$emit('insert', template.html)
}
}
}
</script>
样式隔离 使用 Scoped CSS 和 BEM 命名规范:
/* 编辑器样式 */
.editor-container >>> .ql-container {
font-family: 'PingFang SC';
}
/* 模板样式 */
.xiumi-template {
margin: 10px 0;
border: 1px dashed #eee;
}
与后端数据交互
实现内容保存和加载:
// API 方法
export default {
methods: {
async saveContent() {
await axios.post('/api/content', { html: this.content })
},
async loadContent(id) {
const res = await axios.get(`/api/content/${id}`)
this.content = res.data.html
}
}
}
移动端适配
添加响应式处理:
// 检测设备类型
const isMobile = window.innerWidth < 768
// 动态调整工具栏
editorOptions: {
toolbar: isMobile ?
[['bold', 'italic']] :
fullToolbarOptions
}
以上方案提供了在 Vue 中实现类似秀米编辑器的基本框架,可根据实际需求扩展更多功能如素材库、多列布局等。核心在于结合现有富文本编辑器进行二次开发,通过组件化方式实现模板系统。







