使用第三方库
第三方库地址为:https://github.com/jonexyz/wang-editor-v5
具体使用方式该库有使用说明,这里就不再赘述
无法访问github的,我放了个截图在文章最后
自主整合
业务需求和该第三方库不太一样需要修改时,如果修改第三方库的代码,弊端较多,所以就需要整合成本地代码。看步骤
- 在public/vendor下创建wangEditor5(自己可以随意起名)
- 在该目录下引入dist/css/style.css和dist/index.js文件,参考文档https://www.wangeditor.com/v5/installation.html#npm
- 在resources/views/admin下创建wangEditor5.blade.php模板文件
<div class="{{$viewClass['form-group']}} {!! !$errors->has($errorKey) ? '' : 'has-error' !!}">
<label for="{{$id}}" class="{{$viewClass['label']}} control-label">{{$label}}</label>
<div class="{{$viewClass['field']}}">
@include('admin::form.error')
<div style="border: 1px solid #ccc;">
<div id="editor-toolbar-{{$id}}" style="border-bottom: 1px solid #ccc;"></div>
<div id="{{$id}}" style="width: 100%; height: 500px;">
@if(!empty(old($column, $value)))
@else
<p></p>
@endif
</div>
</div>
<input id="input-{{$id}}" type="hidden" name="{{$name}}" value="{{ old($column, $value) }}" />
@include('admin::form.help-block')
</div>
</div>
- 在app/Admin/Extensions下创建WangEditor5.php,可以在下图示例代码上进行修改
namespace 自定义
use Encore\Admin\Form\Field;
class Editor extends Field
{
//模板文件
protected $view = 'admin.wangEditor5';
//引入的js文件
protected static $js = [
'/vendor/WangEditor5/dist/index.js',
];
//引入的css文件
protected static $css = [
'/vendor/WangEditor5/dist/css/style.css',
];
public function render()
{
//设置表单提交需要的token
$token = csrf_token();
//根据官网代码改的js代码
$this->script = <<<EOT
//获取wangEditor
const E{$this->id} = window.wangEditor;
// 切换语言
const LANG{$this->id} = location.href.indexOf('lang=en') > 0 ? 'en' : 'zh-CN';
E{$this->id}.i18nChangeLanguage(LANG{$this->id});
// 初始化
let htmla{$this->id} = document.getElementById('input-{$this->id}').value;
window.editor = E{$this->id}.createEditor({
selector: '#{$this->id}',
html: htmla{$this->id},
config: {
placeholder: '请输入内容',
MENU_CONF: {
uploadImage: {
server:'文件上传路径',
//上传超时时间1分钟
timeout: 60 * 1000,
allowedFileTypes: ['image/*'],
withCredentials: true,
fieldName: 'images[]',
maxFileSize: 10 * 1024 * 1024,
base64LimitSize:0,
meta: {
_token: '$token'
}
}
},
onChange(editor) {
// 赋值给表单接收
if(editor.getHtml()){
document.getElementById('input-{$this->id}').value = editor.getHtml()
}else{
document.getElementById('input-{$this->id}').value = '';
}
}
}
})
window.toolbar = E{$this->id}.createToolbar({
editor,
selector: '#editor-toolbar-{$this->id}',
config: {
excludeKeys:[
'editVideoSize',
'uploadVideo',
'insertVideo',
'group-video',
'fullScreen',
'insertTable',
'codeBlock',
'bulletedList',
'numberedList',
'todo',
'emotion'
]
},
mode: 'simple',
});
EOT;
return parent::render();
}
- 修改app/bootstrap.php文件,添加如下代码,editor虽然可以自定义,但是这里我没有修改,这样我可以不修改其它对应的代码
use Encore\Admin\Form;
Form::extend('editor', \App\Admin\Extensions\WangEditor5::class);
- 使用以下代码完成
protected function form()
{
$form = new Form(new Articles());
$form->text('title', __('Title'));
$form->editor('content', __('Content'));
return $form;
}