以下是一个示例Uniapp富文本编辑器组件的代码:
<template>
<div>
<div>
<van-button type="primary" @click="addText">添加文字</van-button>
<van-button type="primary" @click="addImage">添加图片</van-button>
<van-button type="primary" @click="submit">提交</van-button>
</div>
<div>
<div v-html="content"></div>
</div>
<van-popup v-model="popupVisible" position="bottom">
<div>
<van-uploader :after-read="uploadImage" accept="image/*" multiple />
</div>
</van-popup>
</div>
</template>
<script>
export default {
data() {
return {
content: '',
popupVisible: false
}
},
methods: {
addText() {
this.content += '<p>请输入文字</p>'
},
addImage() {
this.popupVisible = true
},
uploadImage(e) {
const files = e.file
const formData = new FormData()
formData.append('file', files, files.name)
this.$http.post('/api/upload', formData)
.then(response => {
const imageUrl = response.data.imageUrl
this.content += `<img src="${imageUrl}" />`
})
},
submit() {
this.$http.post('/api/submit', { content: this.content })
.then(response => {
// 提交成功
})
}
}
}
</script>
这个组件包含一个可编辑的富文本区域和三个按钮,分别用于添加文字、添加图片和提交内容。添加文字和图片的方法很简单,只需要向content变量中添加HTML标记。上传图片的方法使用了Vanilla UPloader组件,上传完成后在content中插入一个img标记。最后,将编辑器中的内容提交到后端。