Vue集成vue2-editor富文本編輯器

npm安裝vue2-editor

npm install --save vue2-editorphp

引入VueEditor模塊

import { VueEditor } from "vue2-editor"vue

  • ImageDrop是用於圖片拖拽
  • ImageResize是用於調整編輯的圖片尺寸

引入VueEditor組件

components: {
    VueEditor
}
複製代碼

引入vue-editor節點

<vue-editor
          id="editor"
          :editor-options="editorSettings"
          v-model="form.content"
          use-custom-image-handler
          @imageAdded="handleImageAdded"/>
複製代碼
  • 其中v-model綁定的是編輯內容
  • use-custom-image-handler是使用自定義圖片上傳
  • @imageAdded綁定的是自定義上傳的方法代碼以下
handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData()
      formData.append('file', file)
      upload(formData).then(response => {
        if (response.code === 200) {
          const url = getRealPath(response.data.url)
          Editor.insertEmbed(cursorLocation, 'image', url)
          resetUploader()
        } else {
          console.error(response.message)
        }
      // eslint-disable-next-line handle-callback-err
      }).catch(error => {
        console.error(error)
      })
    }
複製代碼
  • response對應上傳返回值,對應json格式是
{code:200, message: 'success', data:{url: uploads/xxxxx.jpg}}
複製代碼
  • 此處的上傳後臺代碼是php將文件保存到uploads目錄下面,而後返回相對路徑,yii代碼也提供一下,供你們參考,命名空間根據本身的代碼修改
<?php
namespace app\common\helper;

use yii\base\BaseObject;

class UploadForm extends Model
{
  public $mFile;

  public function rules()
  {
    return [
      [['mFile'], 'file'],
    ];
  }

  public function upload()
  {
    if ($this->validate()) {
      $path = "uploads/" . date("YmdH", time()) . "/";
      if (!file_exists($path)) {
        mkdir($path, 0777, true);
      }
      $fileName = Yii::$app->getSecurity()->generateRandomString(8) . time();
      $fullPath = $path . $fileName . '.' . $this->mFile->extension;
      $this->mFile->saveAs($fullPath);
      return $fullPath;
    } else {
      return null;
    }
  }
}
複製代碼
<?php

namespace app\common\base;

use Yii;
use yii\web\Controller;
use yii\web\Response;
use app\models\User;
use yii\web\UploadedFile;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;

class BaseController extends Controller
{

  public function behaviors()
  {
    return ArrayHelper::merge([
      [
        'class' => Cors::className(),
      ],
    ], parent::behaviors());
  }

  /**
   * response json to customer
   *
   * @param array $data
   * @param integer $code
   * @param string $message
   * @return void
   */
  public function respJson($data = [], int $code = 200, $message = 'success')
  {
    $response = Yii::$app->response;
    $response->format = Response::FORMAT_JSON;
    $response->data = [
      'code' => $code,
      'message' => $message,
      'data' => $data,
      'timestamp' => time()
    ];
    $response->send();
  }

  /**
   * response json to customer with pagination
   *
   * @param array $data
   * @param object $pagination
   * @param integer $code
   * @param string $message
   * @return void
   */
  public function respPageJson($data = [], $pagination = null, int $code = 200, $message = 'success')
  {
    $response = Yii::$app->response;
    $response->format = Response::FORMAT_JSON;
    $response->data = [
      'code' => $code,
      'message' => $message,
      'data' => $data,
      'pagination' => $pagination,
      'timestamp' => time()
    ];
    $response->send();
  }

  /**
   * get access-token from header
   *
   * @return void
   */
  public function getAccessToken()
  {
    $headers = Yii::$app->request->headers;
    return $headers->has('x-token') ? $headers->get('x-token') : null;
  }

  /**
   * common upload picture
   *
   * @param string $attributeName
   * @param [type] $saveName
   * @return void
   */
  public function commonUpload()
  {
    $model = new UploadForm();
    if (Yii::$app->request->isPost) {
      $model->mFile = UploadedFile::getInstanceByName('file');
      return $model->upload();
    }
  }
}
複製代碼
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\common\base\BaseController;
use yii\base\Exception;
use yii\base\UserException;
use yii\helpers\ArrayHelper;
class SiteController extends BaseController
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return ArrayHelper::merge([
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],

            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['POST'],
                ],
            ],
        ], parent::behaviors());
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionError()
    {
        $exception = Yii::$app->getErrorHandler()->exception;

        if ($exception === null) {
            $exception = new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
        }

        $code = 200;
        if ($exception instanceof HttpException) {
            $code = $exception->statusCode;
        } else {
            $code = $exception->getCode();
        }

        $exceptionName = Yii::t('yii', 'Error');
        if ($exception instanceof Exception) {
            $exceptionName = $exception->getName();
        }

        $exceptionMessage = Yii::t('yii', 'An internal server error occurred.');
        if ($exception instanceof UserException) {
            $exceptionMessage = $exception->getMessage();
        }
        $this->respJson(null, $code, $exceptionName . ':' . $exceptionMessage);
    }

    /** Upload file */
    public function actionUpload() {
        $saveResult = $this->commonUpload();
        if ($saveResult) {
            $this->respJson(['url' => $saveResult]);
        } else {
            $this->respJson(null, 400, 'upload failed, please try agin later.');
        }
    }
}
複製代碼
  • 完成上面的步驟之後已經能夠進行基礎的編輯以及插入圖片了,若是須要擴展功能,如圖片的縮放,請繼續往下看

npm安裝quill-image-drop-module quill-image-resize-module

npm install --save quill-image-drop-module quill-image-resize-modulewebpack

配置webpack插件

  • 在webpack.dev.conf.js加入
new webpack.ProvidePlugin({
      'window.Quill': 'quill/dist/quill.js',
      'Quill': 'quill/dist/quill.js'
    }),
複製代碼

  • 在webpack.prod.conf.js也加入
new webpack.ProvidePlugin({
      'window.Quill': 'quill/dist/quill.js',
      'Quill': 'quill/dist/quill.js'
    }),
複製代碼

vue-editor綁定設置

editorSettings: {
        modules: {
          imageDrop: true,
          imageResize: {}
        }
      },
複製代碼

到此集成結束上一張效果圖:)

相關文章
相關標籤/搜索