vue2中wangeditor富文本框的使用
·
1.npm依赖下载:
npm install wangeditor@^4.7.15 --save
2.在所需要用到的界面引入(这里是局部引入):
import E from "wangeditor"
3.定义一个要绑定的字段(这个字段在数据库中存储的数据样式为html代码)
return {
answer: '',
}
4.添加数据和修改数据的方法中添加方法
handAdd():当你点击添加方法时要触发的方法
handleEdit():当你点击编辑按钮时要触发的方法
save():当你确定要提交时要触发的方法
handleAdd() { // 新增数据
this.form = {} // 新增数据的时候清空数据
this.fromVisible = true // 打开弹窗
this.setRichText('')
},
handleEdit(row) { // 编辑数据
this.form = JSON.parse(JSON.stringify(row))
this.fromVisible = true // 打开弹窗
this.setRichText(this.form.answer)
},
save() { // 保存按钮触发的逻辑 它会触发新增或者更新
this.$refs.formRef.validate((valid) => {
if (valid) {
this.form.answer = this.editor.txt.html()
this.$request({
url: this.form.id ? '/question/update' : '/question/add',
method: this.form.id ? 'PUT' : 'POST',
data: this.form
}).then(res => {
if (res.code === '200') { // 表示成功保存
this.$message.success('保存成功')
this.load(1)
this.fromVisible = false
} else {
this.$message.error(res.msg) // 弹出错误的信息
}
})
}
})
},
5.定义要操作文本框对象的方法
setRichText(html) {
this.$nextTick(() => {
this.editor = new E(`#editor`)
this.editor.config.uploadImgServer = this.$baseUrl + '/files/editor/upload'
this.editor.config.uploadFileName = 'file'
this.editor.config.uploadImgHeaders = {
token: this.user.token
}
this.editor.config.uploadImgParams = {
type: 'img',
}
this.editor.create() // 创建
this.editor.txt.html(html)
})
},
preview(answer) {
this.answer = answer
this.fromVisible1 = true
},
6.后台添加上传文件的代码:(上传的目录根据自己的需要改写)
/**
* 富文本文件上传
*/
@PostMapping("/editor/upload")
public Dict editorUpload(MultipartFile file) {
String flag;
synchronized (FileController.class) {
flag = System.currentTimeMillis() + "";
ThreadUtil.sleep(1L);
}
String fileName = file.getOriginalFilename();
try {
if (!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
// 文件存储形式:时间戳-文件名
FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName); // ***/manager/files/1697438073596-avatar.png
System.out.println(fileName + "--上传成功");
} catch (Exception e) {
System.err.println(fileName + "--文件上传失败");
}
String http = "http://" + ip + ":" + port + "/files/";
return Dict.create().set("errno", 0).set("data", CollUtil.newArrayList(Dict.create().set("url", http + flag + "-" + fileName)));
}
7.前端完整参考界面
<template>
<div>
<div class="search">
<el-input placeholder="请输入题名查询" style="width: 200px" v-model="questionName"></el-input>
<el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
<el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
</div>
<div class="operation">
<el-button type="primary" plain @click="handleAdd">新增</el-button>
<el-button type="danger" plain @click="delBatch">批量删除</el-button>
</div>
<div class="table">
<el-table :data="tableData" stripe @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center"></el-table-column>
<el-table-column prop="id" label="序号" width="80" align="center" sortable></el-table-column>
<el-table-column prop="questionName" label="题目名称" show-overflow-tooltip></el-table-column>
<el-table-column prop="sort" label="排序" show-overflow-tooltip></el-table-column>
<el-table-column label="参考回答">
<template v-slot="scope">
<el-button @click="preview(scope.row.answer)">查看内容</el-button>
</template>
</el-table-column>
<!-- <el-table-column prop="creatTime" label="创建时间"></el-table-column>
<el-table-column prop="updateTime" label="修改时间"></el-table-column> -->
<el-table-column label="操作" width="180" align="center">
<template v-slot="scope">
<el-button plain type="primary" @click="handleEdit(scope.row)" size="mini">编辑</el-button>
<el-button plain type="danger" size="mini" @click='del(scope.row.id)'>删除</el-button>
</template>
</el-table-column>
</el-table>
<div class="pagination">
<el-pagination background @current-change="handleCurrentChange" :current-page="pageNum"
:page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, prev, pager, next" :total="total">
</el-pagination>
</div>
</div>
<el-dialog title="信息" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
<el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef">
<el-form-item prop="questionName" label="题目名称">
<el-input v-model="form.questionName" autocomplete="off"></el-input>
</el-form-item>
<el-form-item prop="typeId" label="题目分类">
<el-select v-model="form.typeId" placeholder="请选择分类" style="width: 100%">
<el-option v-for="item in types" :label="item.typeName" :value="item.id"
:key="item.id"></el-option>
</el-select>
</el-form-item>
<el-form-item prop="tagId" label="题目标签">
<el-select v-model="form.typeId" placeholder="请选择分类" style="width: 100%">
<el-option v-for="item in types" :label="item.typeName" :value="item.id"
:key="item.id"></el-option>
</el-select>
</el-form-item>
<el-form-item prop="sort" label="排序">
<el-input v-model="form.sort" type="number" min="1" autocomplete="off"
@input="validateInput"></el-input>
</el-form-item>
<el-form-item prop="answer" label="参考答案">
<div id="editor"></div>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="fromVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</div>
</el-dialog>
<el-dialog title="参考答案" :visible.sync="fromVisible1" width="50%" :close-on-click-modal="false" destroy-on-close>
<div class="w-e-text">
<div v-html="answer"></div>
</div>
<div slot="footer" class="dialog-footer">
<el-button @click="fromVisible1 = false">关 闭</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import E from "wangeditor"
export default {
name: "Tiku",
data() {
return {
answer: '',
types: [],
tableData: [], // 所有的数据
pageNum: 1, // 当前的页码
pageSize: 10, // 每页显示的个数
total: 0,
questionName: null,
fromVisible: false,
fromVisible1: false,
form: {},
user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
rules: {
questionName: [{
required: true,
message: '请输入标题',
trigger: 'blur'
}, ],
},
ids: []
}
},
created() {
this.load(1)
this.loadType();
},
methods: {
//监听排序整数 的输入
validateInput() {
if (this.form.sort <= 0) {
this.form.sort = '';
}
},
handleAdd() { // 新增数据
this.form = {} // 新增数据的时候清空数据
this.fromVisible = true // 打开弹窗
this.setRichText('')
},
handleEdit(row) { // 编辑数据
this.form = JSON.parse(JSON.stringify(row)) // 给form对象赋值 注意要深拷贝数据
this.fromVisible = true // 打开弹窗
this.setRichText(this.form.answer)
},
save() { // 保存按钮触发的逻辑 它会触发新增或者更新
this.$refs.formRef.validate((valid) => {
if (valid) {
this.form.answer = this.editor.txt.html()
this.$request({
url: this.form.id ? '/question/update' : '/question/add',
method: this.form.id ? 'PUT' : 'POST',
data: this.form
}).then(res => {
if (res.code === '200') { // 表示成功保存
this.$message.success('保存成功')
this.load(1)
this.fromVisible = false
} else {
this.$message.error(res.msg) // 弹出错误的信息
}
})
}
})
},
setRichText(html) {
this.$nextTick(() => {
this.editor = new E(`#editor`)
this.editor.config.uploadImgServer = this.$baseUrl + '/files/editor/upload'
this.editor.config.uploadFileName = 'file'
this.editor.config.uploadImgHeaders = {
token: this.user.token
}
this.editor.config.uploadImgParams = {
type: 'img',
}
this.editor.create() // 创建
this.editor.txt.html(html)
})
},
preview(answer) {
this.answer = answer
this.fromVisible1 = true
},
del(id) { // 单个删除
this.$confirm('您确定删除吗?', '确认删除', {
type: "warning"
}).then(response => {
this.$request.delete('/question/delete/' + id).then(res => {
if (res.code === '200') { // 表示操作成功
this.$message.success('操作成功')
this.load(1)
} else {
this.$message.error(res.msg) // 弹出错误的信息
}
})
}).catch(() => {})
},
handleSelectionChange(rows) { // 当前选中的所有的行数据
this.ids = rows.map(v => v.id) // [1,2]
},
delBatch() { // 批量删除
if (!this.ids.length) {
this.$message.warning('请选择数据')
return
}
this.$confirm('您确定批量删除这些数据吗?', '确认删除', {
type: "warning"
}).then(response => {
this.$request.delete('/question/delete/batch', {
data: this.ids
}).then(res => {
if (res.code === '200') { // 表示操作成功
this.$message.success('操作成功')
this.load(1)
} else {
this.$message.error(res.msg) // 弹出错误的信息
}
})
}).catch(() => {})
},
load(pageNum) { // 分页查询
if (pageNum) this.pageNum = pageNum
this.$request.get('/question/selectPage', {
params: {
pageNum: this.pageNum,
pageSize: this.pageSize,
questionName: this.questionName,
}
}).then(res => {
console.log(res.data.list)
this.tableData = res.data?.list
this.total = res.data?.total
})
},
reset() {
this.questionName = null
this.load(1)
},
handleCurrentChange(pageNum) {
this.load(pageNum)
},
loadType() {
this.$request.get('/question/selectAll').then(res => {
this.types = res.data
})
},
handleAvatarSuccess(response, file, fileList) {
this.form.img = response.data
},
}
}
</script>
<style scoped>
</style>
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)