看完本文,你将有至少3个?收获:
- 感受setup语法糖的魅力
- 获得ckeditor的vue3组件
- 学会父组件调用子组件方法
使用Vite构建Vue3项目
Vite是一个由原生ES模块驱动的Web开发构建工具,支持模块热更新和按需加载。用尤大的话来讲,用了Vite之后就可以告别webpack 了。
用命令行工具进入项目存放目录,执行下面命令构建项目名称为vue3_ckeditor5。
npm init vite@latest vue3_ckeditor5 -- --template vue
然后键盘上下键选择“vue”框架,回车。
然后选择js语言的vue,回车。
看到“Done. Now run”后,说明项目已创建成功。接下来,进入项目目录、安装依赖、运行。
cd vue3_ckeditor5
npm install --registry=https://registry.npm.taobao.org
npm run dev
在浏览器中打开http://localhost:3000/,看到如下信息说明运行成功。
集成CKEditor5
接下来在VSCode中打开vue3_ckeditor5项目,在终端输入下面的命令,安装ckeditor5依赖组件。
npm install --save @ckeditor/ckeditor5-vue @ckeditor/ckeditor5-build-classic
打开src/main.js编辑
import CKEditor from '@ckeditor/ckeditor5-vue'; //此行新增
//下行新增 .use( CKEditor )
createApp(App).use( CKEditor ).mount('#app')
在src\components下新建CKEditor5.vue组件,该组件可以在其它项目中复用。
<template>
<div>
<div id="toolbar-container"></div>
<div id="editor"></div>
</div>
</template>
<script setup>
import { ref, defineExpose } from 'vue';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
let editor = ref();
//方法:初始化ck编辑器
function initCKEditor(val) {
ClassicEditor.create(document.querySelector('#editor'))
.then(newEditor => {
const toolbarContainer = document.querySelector('#toolbar-container');
toolbarContainer.appendChild(newEditor.ui.view.toolbar.element);
editor = newEditor;
newEditor.setData(val);
}).catch(error => {
console.error(error);
});
}
//方法:获得编辑器内容数据
function getContent() {
return editor.getData();
}
//对外暴露两个方法
defineExpose({
initCKEditor,
getContent,
})
</script>
打开App.vue修改
<script setup>
import CKEditor5 from './components/CKEditor5.vue';
import { onMounted } from '@vue/runtime-core';
import { ref } from 'vue';
const editor = ref(); //变量名必须与template里的ref引用名相同
function getContent() {
let content = editor.value.getContent(); //调用子组件的getContent方法
alert(content);
}
onMounted(() => {
const val = "<p>script setup 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。相比于普通的 script 语法,它具有更多优势:</p>" +
"<ul>" +
"<li>更少的样板内容,更简洁的代码。</li>" +
"<li>能够使用纯 Typescript 声明 props 和抛出事件。</li>" +
"<li>更好的运行时性能 (其模板会被编译成与其同一作用域的渲染函数,没有任何的中间代理)。</li>" +
"<li>更好的 IDE 类型推断性能 (减少语言服务器从代码中抽离类型的工作)。</li>" +
"</ul>"
editor.value.initCKEditor(val);// 调用子组件initCKEditor方法,初始化编辑器并传初值val。
});
</script>
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<br />
<button @click="getContent">得到内容</button>
<br />
<br />
<CKEditor5 ref="editor" />
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
注意:调用子组件的initCKEditor方法必须放在onMounted方法中,也就是要页面加载完毕后才能调用子组件方法。
运行结果如下图所示。
?总结
- setup语法糖确实简洁方便,强烈推荐。
- 文中的CKEditor5.vue文件就是vue3的可复用组件
参考:
https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/frameworks/vuejs-v3.html
【本文结束】
学习过程记录,有需要的朋友可以参考。欢迎一键三连(点赞、关注、评论)。