此處使用的是vue2.X,如果是vue3的話安裝方式可能不一樣
安裝
// vue2.X只能安裝低版本
npm install tinymce@5.1.0 -S
npm install @tinymce/tinymce-vue@3.0.1 -S
使用
需要漢化的話要去官網(wǎng)下載中文包洲押,然后將langs放到根目錄的public下面,方便引用
https://www.tiny.cloud/get-tiny/language-packages/
<editor :init="editorInit" />
import Editor from "@tinymce/tinymce-vue";
export default {
components: {
Editor,
},
data() {
let _this = this;
return {
// 這是配置
editorInit: {
height: 500,
// 中文
language_url: "/langs/zh_CN.js",
language: "zh_CN",
// 插件圆凰,此處是圖片上傳和粘貼
plugins: [ "image", "paste"],
// word支持
powerpaste_word_import: "merge",
// 允許直接粘貼data圖片
paste_data_images: true,
// 自定義上傳方法
images_upload_handler: function (file, successFun, failFUn) {
// 可以轉(zhuǎn)為base64
console.log(file.base64());
// 也可以轉(zhuǎn)為blob杈帐,但是直接轉(zhuǎn)blob在粘貼圖片時(shí)文件有問題
// 所以只能先使用base64,再轉(zhuǎn)回blob后進(jìn)行上傳........
console.log(file.blob());
// 將base64轉(zhuǎn)為blob专钉,后面的文件名隨便寫挑童,反正上傳oss的時(shí)候要生成隨機(jī)文件名
let f = _this.dataURLtoFile(file.base64(), "123.png");
// 自己封的上傳方法,采用callback形式返回?cái)?shù)據(jù)
_this.fileToOss(f, (url) => {
// 上傳成功后調(diào)用插件api跃须,將圖片替換到富文本中
successFun(url);
});
},
},
ossData: [],
};
},
created() {
// 獲取后臺(tái)給你的STS配置數(shù)據(jù)
this.getSts();
},
methods: {
// 獲取后臺(tái)給你的STS配置數(shù)據(jù)
getSts() {
let _this = this;
this.request
.post(this.api.sts)
.then((res) => {
_this.ossData = res;
});
},
// base64轉(zhuǎn)blob
dataURLtoFile(dataurl, filename) {
var mime = "png",
bstr = atob(dataurl),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
},
// 自己封裝的上傳方法
fileToOss(file, callBack = () => {}) {
const OSS = require("ali-oss");
const client = new OSS({
region: "oss-cn-beijing",
accessKeyId: this.ossData.AccessKeyId,
accessKeySecret: this.ossData.AccessKeySecret,
stsToken: this.ossData.SecurityToken,
refreshSTSToken: async () => {
const info = await fetch(this.ossData.StsServer);
return {
accessKeyId: info.accessKeyId,
accessKeySecret: info.accessKeySecret,
stsToken: info.stsToken,
};
},
// 刷新臨時(shí)訪問憑證的時(shí)間間隔站叼,單位為毫秒。
refreshSTSTokenInterval: 300000,
bucket: this.ossData.bucket,
});
const data = file;
let _this = this;
async function putObject() {
try {
// 后綴
let fileType = file.name.split(".").pop();
const result = await client.put(
"icon/" + _this.createKey(32) + "." + fileType,
data
);
callBack(result.url);
} catch (e) {
_this.$message.error("圖片上傳失敗菇民,請(qǐng)稍后重試");
}
}
putObject();
},
// 生成隨機(jī)文件名的方法
createKey(length) {
const data = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
];
let nums = "";
for (let i = 0; i < length; i++) {
const r = parseInt(Math.random() * 61, 10);
nums += data[r];
}
return nums;
},
}
......
}