Tincymce

1. 新建一个Tinymce文件夹

2. 分别建立index.vue,plugins.js,toolbar.js,dynamicLoadScript.js文件

index.vue

<template>
  <div
    :class="{ fullscreen: fullscreen }"
    class="tinymce-container"
    :style="{ width: containerWidth }"
  >
    <textarea :id="tinymceId" class="tinymce-textarea" />
  </div>
</template>

<script setup>
import plugins from './plugins';
import toolbar from './toolbar';
import load from './dynamicLoadScript';
import {
  ref,
  watch,
  computed,
  onMounted,
  onActivated,
  onDeactivated,
  onBeforeUnmount,
} from 'vue';
const emit = defineEmits();
const tinymceCDN =
  'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js';
const props = defineProps({
  id: {
    type: String,
    default: () => {
      return (
        'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      );
    },
  },
  value: {
    type: String,
    default: '',
  },
  toolbar: {
    type: Array,
    required: false,
    default: () => [],
  },
  menubar: {
    type: String,
    default: 'file edit insert view format table',
  },
  height: {
    type: [Number, String],
    required: false,
    default: 360,
  },
  width: {
    type: [Number, String],
    required: false,
    default: 'auto',
  },
});
// 响应式数据
const hasChange = ref(false);
const hasInit = ref(false);
const tinymceId = ref(props.id);
const fullscreen = ref(false);
const languageTypeList = {
  en: 'en',
  zh: 'zh_CN',
  es: 'es_MX',
  ja: 'ja',
};
// 计算属性
const containerWidth = computed(() => {
  const width = props.width;
  if (/^[\d]+(\.[\d]+)?$/.test(width)) {
    return `${width}px`;
  }
  return width;
});
// 监听value变化
watch(
  () => props.value,
  (val) => {
    if (!hasChange.value && hasInit.value) {
      nextTick(() => {
        const editor = window.tinymce.get(tinymceId.value);
        if (editor) {
          editor.setContent(val || '');
        }
      });
    }
  }
);
onMounted(() => {
  init();
});
onActivated(() => {
  if (window.tinymce) {
    initTinymce();
  }
});
onDeactivated(() => {
  destroyTinymce();
});
onBeforeUnmount(() => {
  destroyTinymce();
});
const init = () => {
  load(tinymceCDN, (err) => {
    if (err) {
      console.error(err.message);
      return;
    }
    initTinymce();
  });
};
const initTinymce = () => {
  window.tinymce.init({
    selector: `#${tinymceId.value}`,
    language: languageTypeList['zh'],
    height: props.height,
    body_class: 'panel-body ',
    object_resizing: false,
    toolbar: props.toolbar.length > 0 ? props.toolbar : toolbar,
    menubar: props.menubar,
    plugins: plugins,
    end_container_on_empty_block: true,
    powerpaste_word_import: 'clean',
    code_dialog_height: 450,
    code_dialog_width: 1000,
    advlist_bullet_styles: 'square',
    advlist_number_styles: 'default',
    imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
    default_link_target: '_blank',
    link_title: false,
    nonbreaking_force_tab: true,
    init_instance_callback: (editor) => {
      if (props.value) {
        editor.setContent(props.value);
      }
      hasInit.value = true;
      editor.on('NodeChange Change KeyUp SetContent', () => {
        hasChange.value = true;
        emit('input', editor.getContent());
      });
    },
    setup: (editor) => {
      editor.on('FullscreenStateChanged', (e) => {
        fullscreen.value = e.state;
      });
    },
    convert_urls: false,
    images_upload_handler: (blobInfo, success, failure, progress) => {
      var xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open('POST', '你自己的上传图片的接口地址');
      xhr.upload.onprogress = function (e) {
        progress((e.loaded / e.total) * 100);
      };
      xhr.onload = function () {
        var json;
        if (xhr.status == 403) {
          failure('HTTP Error: ' + xhr.status, { remove: true });
          return;
        }
        if (xhr.status < 200 || xhr.status >= 300) {
          failure('HTTP Error:' + xhr.status);
        }
        json = JSON.parse(xhr.responseText);
        if (!json || typeof json.data != 'string') {
          failure('Invalid JSON: ' + xhr.responseText);
          return;
        }
        success(json.data);
      };
      xhr.onerror = function () {
        failure(
          'Image upload failed due to a XHR Transport error. Code: ' +
            xhr.status
        );
      };

      var formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());
      formData.append('shopId', '0');
      xhr.send(formData);
    },
    file_picker_callback: function (callback, value, meta) {
      var filetype =
        '.pdf,.txt,.zip,.rar,.7z,.docx,.xls,.xlsx,.ppt,.pptx,.mp3,.mp4';
      var upurl = 'upimg.php';
      switch (meta.filetype) {
        case 'image':
          filetype = '.jpg,.jpeg,.png,.gif';
          upurl = 'upimg.php';
          break;
        case 'media':
          filetype = '.mp3,.mp4';
          upurl = 'upfile.php';
          break;
        case 'file':
        default:
      }

      var input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('accept', filetype);
      input.click();
      input.onchange = function () {
        var file = this.files[0];
        var xhr, formData;
        console.log(file.name);
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', upurl);
        xhr.onload = function () {
          var json;
          if (xhr.status != 200) {
            alert('HTTP Error: ' + xhr.status);
            return;
          }
          json = JSON.parse(xhr.responseText);
          if (!json || typeof json.location != 'string') {
            alert('Invalid JSON: ' + xhr.responseText);
            return;
          }
          callback(json.location);
        };
        formData = new FormData();
        formData.append('file', file, file.name);
        xhr.send(formData);
      };
    },
  });
};

const destroyTinymce = () => {
  const tinymce = window.tinymce.get(tinymceId.value);
  if (fullscreen.value) {
    tinymce.execCommand('mceFullScreen');
  }
  if (tinymce) {
    tinymce.destroy();
  }
};
</script>
<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
</style>

plugins.js

const plugins = [
  'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount',
];

export default plugins;

toolbar.js

const toolbar = [
  'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
  'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen',
];

export default toolbar;

dynamicLoadScript.js

let callbacks = [];

function loadedTinymce() {
  return window.tinymce;
}

const dynamicLoadScript = (src, callback) => {
  const existingScript = document.getElementById(src);
  const cb = callback || function () {};

  if (!existingScript) {
    const script = document.createElement('script');
    script.src = src;
    script.id = src;
    document.body.appendChild(script);
    callbacks.push(cb);
    const onEnd = 'onload' in script ? stdOnEnd : ieOnEnd;
    onEnd(script);
  }

  if (existingScript && cb) {
    if (loadedTinymce()) {
      cb(null, existingScript);
    } else {
      callbacks.push(cb);
    }
  }

  function stdOnEnd(script) {
    script.onload = function () {
      this.onerror = this.onload = null;
      for (const cb of callbacks) {
        cb(null, script);
      }
      callbacks = null;
    };
    script.onerror = function () {
      this.onerror = this.onload = null;
      cb(new Error('Failed to load ' + src), script);
    };
  }

  function ieOnEnd(script) {
    script.onreadystatechange = function () {
      if (this.readyState !== 'complete' && this.readyState !== 'loaded')
        return;
      this.onreadystatechange = null;
      for (const cb of callbacks) {
        cb(null, script);
      }
      callbacks = null;
    };
  }
};

export default dynamicLoadScript;

3. 在需要的位置使用

<template>
  <Tinymce height="300" />
</template>
<script setup>
import Tinymce from '@/components/Tinymce/index.vue';
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值