CKEditorとVueの相性が悪いと呟いたら
はじめに
VueとCKEDITOR食い合わせ悪そう
— やまうち(つ)Д゚) (@tsyama_desu) 2019年6月17日
こんなことを呟いたら
Translate doesn't work so well but if you're looking for Vue integration here it is for CKEditor 5 😉https://t.co/UoENkD960Y
— CKEditor Ecosystem (@ckeditor) 2019年6月17日
CKEditor公式っぽいアカウントからこんな返信が来ました。
雰囲気訳:「翻訳うまくできてないけど、Vueと統合したいならここ見てCKEditor5使うといいよ😉」
ありがてえ…
これはブログにしなければ…
今回の環境
docker-compose.ymlこんな感じです
version: '3' services: web: image: 'httpd:2.4' volumes: - './web-data/:/usr/local/apache2/htdocs/' ports: - '80:80'
まずは普通に
まず何も考えずにCKEditorとVueを導入してみようとします。
はじめにCKEditor。
<script src="https://cdn.ckeditor.com/ckeditor5/12.2.0/classic/ckeditor.js"></script> <script src="https://cdn.ckeditor.com/ckeditor5/12.2.0/classic/translations/ja.js">
<head>
タグ内でCDNのjsファイルを読み込み、
<textarea name="content" id="editor"></textarea>
<textarea>
に適当なidを付け、
<script> ClassicEditor .create(document.querySelector( '#editor' ), { language: 'ja' }); </script>
ClassicEditor.create()
を呼び出します。簡単ですね。
次にVue.js。
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
こちらもCDNでjsファイルを読み込み、
<div id="app"> <textarea name="content" id="editor">{{ msg }}</textarea> <button v-on:click="sayHello">ボタン</button> </div>
Vueを適用させたい要素に適当なidを指定して、
<script> new Vue({ el: "#app", data: { msg: "Welcome" }, methods: { sayHello(){ this.msg = "Hello!" } } }) </script>
Vueインスタンスを作ります。
一見うまく導入できたようにも見えますが、CKEditorがうまく動きません。
やはりバカ正直には導入できないようです。
公式に教えてもらったやつ
それでは公式に教えてもらった英語のマニュアルを見ていきます。
npmでインストールするので、Dockerにnpmを入れておきましょう。参考記事はこちら。
npm install --save @ckeditor/ckeditor5-vue @ckeditor/ckeditor5-build-classic
npmでckeditor5-vue
とckeditor5-build-classic
をインストールします。
インストールできたらjsファイルを直接読み込み、
<script src="./node_modules/@ckeditor/ckeditor5-build-classic/build/ckeditor.js"></script> <script src="./node_modules/@ckeditor/ckeditor5-vue/dist/ckeditor.js"></script>
Vue.use(CKEditor);
を宣言すると、コンポーネントの要領で<ckeditor>
が使えるようになります。最終的にはこんな感じになりました。
<!DOCTYPE html> <html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>test</title> <script src="./node_modules/@ckeditor/ckeditor5-build-classic/build/ckeditor.js"></script> <script src="./node_modules/@ckeditor/ckeditor5-vue/dist/ckeditor.js"></script> </head> <body> <div id="app"> <ckeditor :editor="editor" v-model="editorData" :config="editorConfig"></ckeditor> <button v-on:click="sayHello">ボタン</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script> Vue.use(CKEditor); new Vue({ el: "#app", data: { msg: "Welcome", editor: ClassicEditor, editorData: '<p>Content of the editor.</p>', editorConfig: { language: 'ja' } }, methods: { sayHello(){ this.editorData = "<p>Hello!</p>" } } }) </script> </body> </html>
これでCKEditorを使いつつVueも導入できるようになりましたね。おめでとう。
おわりに
他にももうちょっと手の込んだ導入方法あるのであとは公式のマニュアルをどうぞ。