写在最前

小型项目中 使用VUE 和 uniapp 开发 使用uniCloud作为云开发服务 技术栈为VUE3+uniapp3+uniCloud,第一个项目纯手撸没用模板框架,应该考虑tdesign的

一、组件通信

  1. 父子组件通信
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 父组件 -->
<template>
<child-component :msg="message" @onCallback="handleCallback"/>
</template>

<!-- 子组件 -->
<script>
export default {
props: {
msg: String
},
methods: {
sendToParent() {
this.$emit('onCallback', '来自子组件的数据')
}
}
}
</script>

二、状态管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// store/index.js
import { createStore } from 'vuex'

export default createStore({
state: {
userInfo: null
},
mutations: {
SET_USER_INFO(state, userInfo) {
state.userInfo = userInfo
}
},
actions: {
async getUserInfo({ commit }) {
const userInfo = await uniCloud.callFunction({
name: 'getUserInfo'
})
commit('SET_USER_INFO', userInfo)
}
}
})

三、常用工具函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// utils/index.js
export const formatDate = (date, fmt = 'yyyy-MM-dd hh:mm:ss') => {
// 日期格式化
}

export const showToast = (title, duration = 2000) => {
uni.showToast({
title,
duration,
icon: 'none'
})
}

export const navigateTo = (url) => {
uni.navigateTo({
url
})
}

四、全局化富文本编辑器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
<template>
<view class="editor-container">
<!-- 非全屏状态的编辑器 -->
<view class="editor-box" v-if="!editorFullscreen">
<editor
class="editor"
:id="editorId"
:placeholder="placeholder"
@ready="onEditorReady"
@input="onEditorInput"
@statuschange="onStatusChange"
></editor>
<view class="fullscreen-btn" @tap="enterFullscreen">
<text class="iconfont">&#xe623;</text>
<text class="btn-text">全屏编辑</text>
</view>
</view>

<!-- 全屏状态的编辑器 -->
<view v-if="editorFullscreen" class="editor-fullscreen">
<view class="editor-toolbar">
<view
class="tool-item"
:class="{ active: formats.bold }"
@tap="execCommand('bold')"
>
<text class="iconfont">&#xe61f;</text>
<text class="tool-tip">加粗</text>
</view>
<view
class="tool-item"
:class="{ active: formats.italic }"
@tap="execCommand('italic')"
>
<text class="iconfont">&#xe61e;</text>
<text class="tool-tip">斜体</text>
</view>
<view
class="tool-item"
:class="{ active: formats.underline }"
@tap="execCommand('underline')"
>
<text class="iconfont">&#xe61d;</text>
<text class="tool-tip">下划线</text>
</view>
<view
class="tool-item"
:class="{ active: formats.header === 1 }"
@tap="execCommand('header', 1)"
>
<text class="iconfont">&#xe623;</text>
<text class="tool-tip">H1</text>
</view>
<view
class="tool-item"
:class="{ active: formats.header === 3 }"
@tap="execCommand('header', 3)"
>
<text class="iconfont">&#xe622;</text>
<text class="tool-tip">H3</text>
</view>
<view
class="tool-item"
:class="{ active: formats.align === 'left' }"
@tap="execCommand('justify', 'left')"
>
<text class="iconfont">&#xe648;</text>
<text class="tool-tip">左对齐</text>
</view>
<view
class="tool-item"
:class="{ active: formats.align === 'center' }"
@tap="execCommand('justify', 'center')"
>
<text class="iconfont">&#xe643;</text>
<text class="tool-tip">居中</text>
</view>
<view
class="tool-item"
:class="{ active: formats.align === 'right' }"
@tap="execCommand('justify', 'right')"
>
<text class="iconfont">&#xe644;</text>
<text class="tool-tip">右对齐</text>
</view>
<view
class="tool-item"
:class="{ active: formats.list === 'ordered' }"
@tap="execCommand('list', 'ordered')"
>
<text class="iconfont">&#xe65b;</text>
<text class="tool-tip">有序列表</text>
</view>
<view
class="tool-item"
:class="{ active: formats.list === 'bullet' }"
@tap="execCommand('list', 'bullet')"
>
<text class="iconfont">&#xe647;</text>
<text class="tool-tip">无序列表</text>
</view>
<view
class="tool-item"
@tap="insertImage"
>
<text class="iconfont">&#xe63e;</text>
<text class="tool-tip">插入图片</text>
</view>
</view>
<editor
class="editor"
:id="fullscreenEditorId"
:placeholder="placeholder"
@ready="onEditorReady"
@input="onEditorInput"
@statuschange="onStatusChange"
></editor>
<view class="return-btn" @tap="exitFullscreen">
<text class="iconfont">&#xe64f;</text>
<text class="btn-text">退出全屏</text>
</view>
</view>
</view>
</template>

<script>
export default {
name: 'RichEditor',

props: {
modelValue: {
type: String,
default: ''
},
placeholder: {
type: String,
default: '请输入内容'
},
editorId: {
type: String,
default: 'editor'
},
fullscreenEditorId: {
type: String,
default: 'editor-fullscreen'
}
},

data() {
return {
editorCtx: null,
editorFullscreenCtx: null,
editorFullscreen: false,
formats: {},
currentContent: ''
}
},

watch: {
modelValue: {
handler(newVal) {
console.log('编辑器modelValue变化:', newVal)
if (newVal !== this.currentContent) {
this.currentContent = newVal
console.log('更新编辑器内容为:', this.currentContent)
this.updateEditorContent()
}
},
immediate: true
}
},

methods: {
updateEditorContent() {
const ctx = this.editorFullscreen ? this.editorFullscreenCtx : this.editorCtx
console.log('准备更新编辑器内容,当前上下文:', ctx ? '存在' : '不存在')
console.log('当前编辑器状态:', {
isFullscreen: this.editorFullscreen,
hasFullscreenCtx: !!this.editorFullscreenCtx,
hasNormalCtx: !!this.editorCtx,
content: this.currentContent
})

if (ctx && this.currentContent !== undefined) {
console.log('开始设置编辑器内容:', this.currentContent)
ctx.setContents({
html: this.currentContent,
success: () => {
console.log('设置编辑器内容成功')
},
fail: (err) => {
console.error('设置编辑器内容失败:', err)
// 失败后重试一次
setTimeout(() => {
console.log('重试设置编辑器内容')
ctx.setContents({
html: this.currentContent,
success: () => console.log('重试设置编辑器内容成功'),
fail: (err) => console.error('重试设置编辑器内容失败:', err)
})
}, 300)
}
})
} else {
console.warn('无法更新编辑器内容:上下文不存在或内容未定义')
}
},

// 编辑器准备就绪
onEditorReady() {
// 添加延时,确保编辑器DOM已经渲染完成
setTimeout(() => {
this.initEditor()
}, 100)
},

// 初始化编辑器
initEditor() {
try {
const query = uni.createSelectorQuery().in(this)
query.select(`#${this.editorFullscreen ? this.fullscreenEditorId : this.editorId}`)
.context((res) => {
console.log('获取编辑器上下文:', res)
if (!res || !res.context) {
console.warn('编辑器上下文不存在,将在300ms后重试')
setTimeout(() => {
this.initEditor()
}, 300)
return
}

if (this.editorFullscreen) {
this.editorFullscreenCtx = res.context
console.log('设置全屏编辑器上下文成功')
} else {
this.editorCtx = res.context
console.log('设置普通编辑器上下文成功')
}

// 初始化完成后设置内容
this.updateEditorContent()
})
.exec()
} catch (e) {
console.error('初始化编辑器失败:', e)
setTimeout(() => {
this.initEditor()
}, 300)
}
},

// 编辑器输入
onEditorInput(e) {
if (!e || !e.detail) return
const html = e.detail.html || ''
console.log('编辑器输入:', html)
this.currentContent = html
this.$emit('update:modelValue', html)
},

// 编辑器状态变化
onStatusChange(e) {
if (!e || !e.detail) return
this.formats = e.detail
},

// 执行编辑器命令
execCommand(name, value = null) {
const ctx = this.editorFullscreen ? this.editorFullscreenCtx : this.editorCtx
if (!ctx) {
console.warn('编辑器未准备好')
return
}

try {
switch(name) {
case 'header':
ctx.format('header', value)
break
case 'justify':
ctx.format('align', value)
break
case 'list':
ctx.format('list', value)
break
default:
ctx.format(name, value)
}
} catch (e) {
console.error('执行编辑器命令失败:', e)
}
},

// 插入图片
insertImage() {
const ctx = this.editorFullscreen ? this.editorFullscreenCtx : this.editorCtx
if (!ctx) {
console.warn('编辑器未准备好')
return
}

uni.chooseImage({
count: 1,
success: (res) => {
uni.showLoading({
title: '上传中...'
})

uniCloud.uploadFile({
filePath: res.tempFilePaths[0],
cloudPath: `content/${Date.now()}-${Math.random().toString(36).slice(-6)}.${res.tempFilePaths[0].split('.').pop()}`
}).then(result => {
ctx.insertImage({
src: result.fileID,
width: '100%',
success: () => {
uni.hideLoading()
},
fail: (err) => {
console.error('插入图片失败:', err)
uni.hideLoading()
uni.showToast({
title: '插入图片失败',
icon: 'none'
})
}
})
}).catch(err => {
console.error('上传图片失败:', err)
uni.hideLoading()
uni.showToast({
title: '上传图片失败',
icon: 'none'
})
})
}
})
},

// 进入全屏
enterFullscreen() {
console.log('进入全屏,当前内容:', this.currentContent)
this.editorFullscreen = true

// 延时等待全屏编辑器渲染完成后设置内容
setTimeout(() => {
const query = uni.createSelectorQuery().in(this)
query.select(`#${this.fullscreenEditorId}`)
.context((res) => {
console.log('获取全屏编辑器上下文:', res)
if (!res || !res.context) {
console.warn('全屏编辑器上下文不存在,将在300ms后重试')
setTimeout(() => {
this.enterFullscreen()
}, 300)
return
}

this.editorFullscreenCtx = res.context
console.log('设置全屏编辑器上下文成功,准备设置内容:', this.currentContent)

// 直接设置内容
if (this.currentContent) {
this.editorFullscreenCtx.setContents({
html: this.currentContent,
success: () => {
console.log('全屏模式:设置内容成功')
},
fail: (err) => {
console.error('全屏模式:设置内容失败', err)
// 失败后重试一次
setTimeout(() => {
console.log('重试设置全屏编辑器内容')
this.editorFullscreenCtx.setContents({
html: this.currentContent,
success: () => console.log('重试设置全屏编辑器内容成功'),
fail: (err) => console.error('重试设置全屏编辑器内容失败:', err)
})
}, 300)
}
})
}
})
.exec()
}, 300) // 增加延时,确保DOM完全渲染
},

// 退出全屏
exitFullscreen() {
console.log('退出全屏,当前内容:', this.currentContent)
this.editorFullscreen = false

// 延时等待主编辑器渲染完成后设置内容
setTimeout(() => {
const query = uni.createSelectorQuery().in(this)
query.select(`#${this.editorId}`)
.context((res) => {
console.log('获取普通编辑器上下文:', res)
if (!res || !res.context) {
console.warn('普通编辑器上下文不存在,将在300ms后重试')
setTimeout(() => {
this.exitFullscreen()
}, 300)
return
}

this.editorCtx = res.context
console.log('设置普通编辑器上下文成功,准备设置内容:', this.currentContent)

// 直接设置内容
if (this.currentContent) {
this.editorCtx.setContents({
html: this.currentContent,
success: () => {
console.log('退出全屏:设置内容成功')
},
fail: (err) => {
console.error('退出全屏:设置内容失败', err)
// 失败后重试一次
setTimeout(() => {
console.log('重试设置普通编辑器内容')
this.editorCtx.setContents({
html: this.currentContent,
success: () => console.log('重试设置普通编辑器内容成功'),
fail: (err) => console.error('重试设置普通编辑器内容失败:', err)
})
}, 300)
}
})
}
})
.exec()
}, 300) // 增加延时,确保DOM完全渲染
}
}
}
</script>

<style lang="scss">
.editor-container {
border: 1rpx solid #eee;
border-radius: 8rpx;
overflow: hidden;
position: relative;
background: #fff;

.editor-box {
width: 100%;
position: relative;

.editor {
width: 100%;
min-height: 400rpx;
background: #fff;
padding: 30rpx;
word-wrap: break-word;
word-break: break-all;
white-space: pre-wrap;
font-size: 28rpx;
line-height: 1.8;
box-sizing: border-box;

:deep() {
img {
max-width: 100% !important;
height: auto !important;
}
}
}

.fullscreen-btn {
position: absolute;
right: 20rpx;
bottom: 20rpx;
background: rgba(0, 0, 0, 0.7);
border-radius: 8rpx;
padding: 12rpx 20rpx;
display: flex;
align-items: center;
gap: 8rpx;
z-index: 1;

.iconfont {
font-size: 28rpx;
color: #fff;
}

.btn-text {
font-size: 24rpx;
color: #fff;
}

&:active {
opacity: 0.8;
}
}
}
}

.editor-fullscreen {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
background: #fff;
display: flex;
flex-direction: column;

.editor-toolbar {
width: 100%;
height: auto;
min-height: 160rpx;
background: #f8f8f8;
border-bottom: 1rpx solid #eee;
padding: 20rpx;
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 16rpx;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 10000;
box-sizing: border-box;

.tool-item {
width: 80rpx;
height: 80rpx;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border-radius: 8rpx;
transition: all 0.3s;
background: #fff;
box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
position: relative;
z-index: 10001;

.iconfont {
font-size: 32rpx;
color: #666;
margin-bottom: 4rpx;
}

.tool-tip {
font-size: 20rpx;
color: #999;
text-align: center;
}

&.active {
background: #e6f7ff;
color: #2979ff;
box-shadow: 0 2rpx 6rpx rgba(41, 121, 255, 0.2);

.iconfont {
color: #2979ff;
}

.tool-tip {
color: #2979ff;
}
}
}
}

.editor {
flex: 1;
width: 100%;
padding: 80rpx 30rpx;
box-sizing: border-box;
margin-top: 160rpx;
height: calc(100vh - 160rpx);
background: #fff;
font-size: 28rpx;
line-height: 1.8;
word-wrap: break-word;
word-break: break-all;
white-space: pre-wrap;
overflow-y: auto;
-webkit-overflow-scrolling: touch;

:deep() {
img {
max-width: 100% !important;
height: auto !important;
}

p {
margin: 0;
padding: 0;
}
}
}

.return-btn {
position: fixed;
left: 30rpx;
bottom: 30rpx;
z-index: 10002;
width: 100rpx;
height: 100rpx;
background: rgba(0, 0, 0, 0.7);
border-radius: 50%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;

.iconfont {
font-size: 40rpx;
color: #fff;
}

.btn-text {
font-size: 20rpx;
color: #fff;
margin-top: 4rpx;
}
}
}
</style>