1. 程式人生 > >仿有贊後臺+vue+ts+vuecli3.0+elementUi 集合看這篇就夠了

仿有贊後臺+vue+ts+vuecli3.0+elementUi 集合看這篇就夠了

前言

最近嘗試了vue+ts的組合個人感覺vue對於ts並沒有特別的像angular2這樣的友好,但是對於ts和js之間個人還是選擇ts的。語法糖來說es6簡直舒爽,下面我詳細介紹下怎麼使用ts+vue。ts+vue的外掛會少上很多,但是肯定會隨著vue對ts的支援外掛也會越來越多當前專案demo預覽(作為一個菜雞畢竟經歷眾多專案可以給一些新手一點提示 (QQ群技術討論)838293023備註(github進來的

游泳健身瞭解一下:githubJQ外掛 技術文件 技術文件會持續更新


內容總結

  1. vue cli3的安裝。
  2. vue config檔案配置
  3. 專案結構檔案搭建
  4. 路由的使用
  5. vue cli啟動以及啟用下載ts 支援vue 的外掛
  6. ts aixo的使用
  7. vue X的使用
  8. 圖片上傳(批量上傳)//ts element的使用
  9. 分頁的使用
  10. 重製按鈕的分裝
  11. 富文字編譯器

1.VueCLI 3.0

VueCLI 3.0 首先安裝node.js自己百度安裝

安裝:

# 然後我們安裝vuecli3.0 npm 或者 yarn都是可以的網上慢的小夥子可以用yarn
npm install -g @vue/cli
# OR
yarn global add @vue/cli
複製程式碼

建立一個專案:

vue create my-project
# OR
vue ui 複製程式碼

  1. 第一個是自己建立過的模版。
  2. 第二個是系統預設的
  3. 第三個自己選配置
    我這邊有建立過一個,我們選紅色選中的這個

我們這樣選擇。空格鍵是否選中,上下選擇

直接回車(默認同意)

一路回車然後選擇package.json 看下我們選擇了啥ts 然後sass 語法檢查esl

然後再回車就進行最後的cli專案的下載了。耐心等待

我們下載好了

# 輸入
vue ui
複製程式碼

歡迎來到vuecli3.0 圖形話介面,現彆著急現看我們的專案檔案結構

2.vue config檔案配置


下面是我們的檔案的結構

  ##  檔案介紹
 
 1.   node_modules //當前node模組存放處
 2.   public //index頁面所在鏡標頭檔案也可以放這個裡面
 3.   src //當前專案存放
        assets //靜態檔案存放
        components //元件存放
        views //專案存放
        app.vue //這個我們檔案的主要路由輸入地方
        main //總的js檔案
        router //路由檔案
        shims-tsx.d //相容jsx
        shims-vue.d //相容vue
        store //vuex總檔案
 4.   pakeage.js //檔案(我們安裝的依賴都再裡面可以看到,也可以根據這個去下載node_modules)
 5.   我們還少一個vue.config.js 和 pakeage.js 同級
複製程式碼
為我等伸手黨送上一份福利
// vue.config.js
module.exports = {
    // 選項...
    // 當使用基於 HTML5 history.pushState 的路由時;
    // 當使用 pages 選項構建多頁面應用時。
    baseUrl:"",
    // 當執行 vue-cli-service build 時生成的生產環境構建檔案的目錄。注意目標目錄在構建之前會被清除 (構建時傳入 --no-clean 可關閉該行為)。
    outputDir:"webApp",
    // 放置生成的靜態資源 (js、css、img、fonts) 的 (相對於 outputDir 的) 目錄。
    assetsDir:"assets",
    // 指定生成的 index.html 的輸出路徑 (相對於 outputDir)。也可以是一個絕對路徑。
    indexPath:"index.html",
    // 預設情況下,生成的靜態資源在它們的檔名中包含了 hash 以便更好的控制快取。然而,這也要求 index 的 HTML 是被 Vue CLI 自動生成的。如果你無法使用 Vue CLI 生成的 index HTML,你可以通過將這個選項設為 false 來關閉檔名雜湊。
    filenameHashing:true,
    // 多頁面
    pages:undefined,
    // 編譯警告
    lintOnSave:false,
    // 是否使用包含執行時編譯器的 Vue 構建版本。設定為 true 後你就可以在 Vue 元件中使用 template 選項了,但是這會讓你的應用額外增加 10kb 左右。
    runtimeCompiler:false,
    // 預設情況下 babel-loader 會忽略所有 node_modules 中的檔案。如果你想要通過 Babel 顯式轉譯一個依賴,可以在這個選項中列出來。
    transpileDependencies:[],
    // 如果你不需要生產環境的 source map,可以將其設定為 false 以加速生產環境構建。
    productionSourceMap:false,
    // 設定生成的 HTML 中 <link rel="stylesheet"> 和 <script> 標籤的 crossorigin 屬性。需要注意的是該選項僅影響由 html-webpack-plugin 在構建時注入的標籤 - 直接寫在模版 (public/index.html) 中的標籤不受影響。
    crossorigin:undefined,
    // 在生成的 HTML 中的 <link rel="stylesheet"> 和 <script> 標籤上啟用 Subresource Integrity (SRI)。如果你構建後的檔案是部署在 CDN 上的,啟用該選項可以提供額外的安全性。需要注意的是該選項僅影響由 html-webpack-plugin 在構建時注入的標籤 - 直接寫在模版 (public/index.html) 中的標籤不受影響。另外,當啟用 SRI 時,preload resource hints 會被禁用,因為 Chrome 的一個 bug 會導致檔案被下載兩次。
    integrity:false,
    // 反向代理
    devServer:{
        // devServer: {
        //     proxy: {
        //       '/api': {
        //         target: '1',
        //         ws: true,
        //         changeOrigin: true
        //       }
        //     }
        // }
    }
}
複製程式碼

vue+ts基本的專案搭建就完成了

3.專案搭建

先看一波完成後的專案介紹(webstorm裡面ts不支援引入vue所有爆紅色,強迫症患者可以用vscode支援會更好)

  public //當前檔案
    static //可以放靜態資源不會被打包(我放的是富文字編譯器的檔案後期會太慢可以換成cdn直接引入到index.html)
  src //當前專案檔案
    assets //靜態資源存放需要被打包
    components //元件存放處
        beforeUpload //單個圖片上傳元件 (基於element)
        pagination //分頁外掛 (基於element)
        reset //重置按鈕元件
        tinyMceEditor //富文字編譯器(這個是重點ts支援的vue外掛當前對於我們伸手黨來說比較少)
        uploadListImg //批量圖片上傳(基於element)
        verification //表單驗證
    utils //當前專案公用方法
    views //當前專案存放地址
        aixo //當前專案ajax封裝
        content //當前專案業務邏輯
        filters //當前專案過濾器
        haveNot //404頁面
        layout //專案結構佈局
        login //當前專案登陸頁面
        method //當前專案的靜態遍歷存放
        store //當前專案vuex存放(不要為了用vuex而用,其實很多專案都不需要用到vuex的)
        system //許可權管理相關
        typings //ts定義使用
        utils //存放其他檔案(我這邊存了cookie的檔案)
    app.vue //全域性路由頁面
    main.ts //啟始的js
    permission.ts //路由中轉頁面
    route //路由頁面
    shims-tsx.d //支援jsx
    shims-vue.d //支援vue
    vue-config //vue配置
    vue-shim.d.ts //宣告全域性方法(ts會自動抓取.d.ts檔案部分全域性方法需要定義才可以使用)
複製程式碼

元件元件後面會一個一個講解,公共方法也會講,先要下載當前需要的ts的外掛

##   最主要到是這3個
1.   aixo
2.   element
3.   js-cookie
複製程式碼

看下package.js 可以看到我們當前到依賴

然後我們去下載當前到依賴


福利篇

教你如何看外掛是否可以使用當前到vue + ts專案(當前ts+vue還是比較少) TypeSearch
如果和下面的圖一樣能搜尋出來的基本可以判斷支援ts


下載當前專案依賴

我們開啟當前圖形管理工具

選擇然後下載(還要下載當前 ts的)
這樣才算把整個 aixo下載好(其他外掛都一樣都需要下載2個)
第二個主要是在 node_modules裡面的 @types裡面定義一遍才可以使用
路由頁面和 vue的頁面差別不是很大
main.js差別也不大

app.vue檔案

講一下這個把 vue-property-decorator不然小夥伴們對這個會很不懂的

### vue-property-decorator
@Prop  父子元件之間傳值
   ## 使用方式
   @Prop({
        type: String,
        default: 'Default Value'
    }) msg: string;
    
@Model  資料雙向繫結
    @Model('change') checked: boolean
    
@Watch  監聽資料變化    
    //監聽路由變化
    @Watch('$route')
    onRouteChanged(route: any, oldRoute: any) :void {
        this.$forceUpdate() ## 重新整理當前的資料
    }
    
@Provide  提供  /  @Inject  注入   
    ## 父
     @Provide('users')
      users = [
        {
          name: 'test',
          id: 0
        }
      ]
    ## 子  
    @Inject('users') users;  

修飾器
    const Log = (msg) => {
      return createDecorator((component, key) => {
        console.log("#Component", component);
        console.log("#Key", key); //log
        console.log("#Msg", msg); //App
      })
    }
    @Log('fullMessage get called')
    get fullMessage() {
      return `${this.message} from Typescript`
    }

複製程式碼

可能您還是不懂建議看下官方文件vue-property-decorator這裡就不詳細贅述了,由於本人比較愚鈍(伸手黨一枚)

我們的專案總的是在 layout資料夾裡面的先看下這個檔案

    layout
        content
            AppMain.vue //當前檔案為我們的主要路由
            index.ts //作為我們的總的轉接的檔案
            navbar.vue //當前專案的左側導航
            newtab.vue //定義的元件
            prompt,vue //最左側的結構(先預留起來)
        layout.vue //總專案的檔案 
        style.scss //當前專案的css
複製程式碼

看我們引入的是一個資料夾,會自動獲取到index.ts然後index.ts裡面es6的寫法

index.ts

## 新寫法ES6 (有時間的老爺可以看下es6)有不懂的可以加群裡面直接詢問專案結構大概就是這樣各位老爺可以github一下即可檢視當前程式碼
    components: {
        Navbar,
        AppMain,
        Prompt
    }
## 老寫法   
    components: {
        Navbar: Navbar,
        AppMain: AppMain,
        Prompt: Prompt
    }
複製程式碼

2.element的引入

1.先安裝依賴

2.引入css

<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
複製程式碼

3.main.ts 引入全域性

4.可以使用了

複製貼上一下element的程式碼

http://element.eleme.io/#/zh-CN/component/time-picker
複製程式碼

我們這邊使用一定要public共有變數, 別使用這個private私有變數(上面的html裡面會找不到下面的變數雖然不會報錯)

5.效果圖

3.aixo的使用(ajax

圖形化介面去下載兩個一個是用來相容 ts

附上封裝好的 ajax程式碼

import Axios from 'axios';
import { Message } from 'element-ui';
import { getToken } from '@/views/utils/auth'; // token 不需要可以不要

const httpServer = (opts: any) => {
        const httpDefaultOpts = { // http預設配置
            method: opts.method,
            baseURL: 'https://xxxx.com',  // 測試
            url: opts.url,
            timeout: 100000,
            params: opts.params,
            data: opts.params,
            headers: opts.method == 'get' ? {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=UTF-8',
            'systoken': '',
            } : {
            'Content-Type': 'application/json;charset=UTF-8' ,
            'systoken': '',
            },
    };
        if (getToken()) {
        const token: any = getToken();
        httpDefaultOpts.headers.systoken = token;
    }
        if (opts.method == 'get') {
        delete httpDefaultOpts.data;
    } else {
        delete httpDefaultOpts.params;
    }
        const promise = new Promise(function(resolve, reject) {
        Axios(httpDefaultOpts).then(
        (res) => {
            if (res.data.code == -3) {
                resolve(res.data);
            } else {
                resolve(res.data);
            }
        },
        ).catch(
        (response) => {
            reject(response);
        },
        );
    });
        return promise;
};

export default httpServer;

複製程式碼
import Http from '@/views/aixo/http';

/**
 * 總系統角色選單 | 根據使用者ID獲取所屬角色的選單
 * @param userId 使用者id
 */
export const managxxxMenuUserId = (userId: any) => {
    return Http({
        url: `/xxx/${userId}`,
        method: 'post',
    });
};

複製程式碼

使用方式

1.vueX的使用(劃重點

首先我們先在圖形話介面去下載當前需要到依賴(版本號以及axios都需要一致不知道可以去我們都第一章看看

先建4個檔案,我一個檔案一個檔案講,觀眾老爺耐心聽

1.state檔案(不瞭解的可以先去看下vuex官網

這裡我們把全域性的變數放裡面(說一下不是為了用vuex才用vuex的,有些專案完全可以不用當然可以不用)

import { getToken, setToken, removeToken } from '@/views/utils/auth'
const state: any = {
    token: getToken(),
    imgUrl: 'https://api.uat.iyuedian.com/iyd-imall-manage/imall/v1/upload'
}
export default state
複製程式碼

2.mutations檔案

這個檔案就是提交改變當前的state裡面的值的不懂interface的可以看下慕課網

export default mutations{
    ## 老方法
    SET_TOKEN(state: any, data: any) {
         state.token = data
    },
 }
 
import { MutationTree } from 'vuex'
    ## 新方法 MutationTree<any> 相信應該有些人不理就是一個介面
const mutations: MutationTree<any> = {
    'SET_TOKEN'(
        state: any,
        data: any
    ): void {
        state.token = data
    }
}
複製程式碼

vuex 裡面的原始碼可以看一下

3.actions檔案

這個檔案可以執行mutations檔案裡面的方法公共的方法都可以放到這個裡面async定義一個一步函式總是實際返回值總是一個 Promise 物件

import { sysUserLogin } from '@/views/interface/login';
import { getToken, setToken, removeToken } from '@/views/utils/auth';
import { ActionTree } from 'vuex';
import { Message } from 'element-ui';

const actions: ActionTree<any, any> = {
    /**
     * 登陸
     * @param param0
     * @param userInfo 登陸資訊
     */
    async Login({state, commit} , userInfo: any) {
        return new Promise((resolve, reject) => {
            sysUserLogin(userInfo).then((response: any) => {
              setToken(response.data.systoken);
              console.log(response.data.systoken);
              commit('SET_TOKEN', response.data.systoken); ## 這邊呼叫了上面的方法
              resolve(response);
            }).catch((error) => {
              reject(error);
            });
          });
      },
    /**
     * 深拷貝
     * @param param0
     * @param params
     */
    async deep({state, commit} , params: any) {
      let obj = {};
      obj = JSON.parse(JSON.stringify(params));
      return obj;
    },

};

export default actions;
複製程式碼

4.getters檔案

getters 可以定義是 store 的計算屬性可以將 state 進行過濾然後return出來

## 老方法
export default {
    token: (state:any) => state.token,
}

## 新方法
import {GetterTree} from 'vuex'
const mutations: GetterTree<any,any> = {
    'token'(
        state: any,
    ): any {
        return state.token
    }
}
export default mutations
複製程式碼

vuex使用方式vuex-class

## 獲取state的值 (先要定義一遍才可以使用)
@State imgUrl
@Action('Login') Login;
@Getter('Login') getterFoo;
@Mutation('Login') mutationFoo;
// 簡寫方式
@State foo
@Getter bar
@Action baz
@Mutation qux
 //最先開始執行 
created() {
    ## 後面的是原來的使用方式
    console.log(this.imgUrl); // ->  this.store.state.imgUrl
    console.log(this.getterFoo(2)) // -> this.store.getters.Login
    this.Login({ value: true }).then() // -> this.store.dispatch('Login', { value: true })
    this.mutationFoo({ value: true }) // -> this.store.commit('Login', { value: true })
}
複製程式碼

2.圖片上傳(以及批量的圖片上傳

這裡我們用的是element的圖片上傳 如有不懂的可以看下element的元件

單張圖片上傳

我們想要更佳簡便的使用方式

// 單張圖片上傳(元件)
<template>
    <div>
        <el-upload
                class="avatar-uploader"
                :action="$store.state.imgUrl" ## 我們圖片上傳的地址
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
            <img v-if="BeforeUploadImg" :src="BeforeUploadImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script lang="ts">

    import { Component, Vue, Model, Watch, Prop } from 'vue-property-decorator';

    @Component
    export default class BeforeUpload extends Vue {

        ## 初始值
        @Prop(String)BeforeUploadImg:string;

        ## 生命週期最先開始執行 void 表示沒有返回值
        created():void {
        }

        public handleAvatarSuccess(res:any, file:any) {
            ## 本地圖片預覽; update: 這樣配合父元件可以實現父子元件的雙向繫結
            this.$emit('update:BeforeUploadImg',res.data[0].newFileName);
        }
        
        public beforeAvatarUpload(file:any) {
            // const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            // if (!isJPG) {
            //     this.$message.error('上傳頭像圖片只能是 JPG 格式!');
            // }
            if (!isLt2M) {
                this.$message.error('上傳頭像圖片大小不能超過 2MB!');
            }
            // return isJPG && isLt2M;
            return isLt2M;
        }
    }
</script>

    # 使用方式
    # html .sync 配合update可以實現雙向繫結
    <BeforeUpload :BeforeUploadImg.sync="BeforeUploadImg"></BeforeUpload>
    
    # script
    import BeforeUpload from '@/components/beforeUpload/beforeUpload.vue';
    import { Component, Vue, Model, Watch, Prop } from 'vue-property-decorator';
    @Component({
        components: {
            BeforeUpload,
        }
    })
    export default class Content extends Vue {
        ## 預設圖片
        public BeforeUploadImg: string = '';
    }

複製程式碼

批量圖片上傳

我們想要更佳簡便的使用方式

// 批量圖片上傳(元件)
<template>
    <div>
        <el-upload
                class="upload-demo"
                :action="$store.state.imgUrl"
                :on-preview="handlePreview"
                :on-success="handleOnSuccess"
                :on-remove="handleRemove"
                :file-list="UploadListsImg"
                list-type="picture">
            <el-button size="small" type="primary">點選上傳</el-button>
            <div slot="tip" class="el-upload__tip">只能上傳jpg/png檔案,且不超過1024kb</div>
        </el-upload>
    </div>
</template>

<script lang="ts">
    import { Component, Vue, Model, Watch, Prop } from 'vue-property-decorator';

    @Component
    export default class UploadListImg extends Vue {
        // 初始值
        @Prop(null)UploadListsImg:object[];
        //最先開始執行
        created():void {
            // tinyMce.init({})
        }
        /**
         * 刪除圖片
         * @param file 刪除的圖片
         * @param fileList 剩下的圖片
         */
        public handleRemove(file:any, fileList:any) {
            console.log(file, fileList);
            this.$emit('update:UploadListsImg',fileList)
            this.$emit('removeListImg',file)
        }
        public handlePreview(file:any) {
            console.log(file);
        }

        /**
         * 新增圖片
         * @param response 成功的返回值
         * @param file 當前的這個圖片
         * @param fileList 當前所有的圖片
         */
        public handleOnSuccess(response:any, file:any, fileList:any){
            file.url = response.data[0].newFileName;
            file.name = response.data[0].originalFilename;
            this.$emit('update:UploadListsImg',fileList)
        }

    }
</script>
    ## html UploadListsImg為當前剩下的圖片的list    removeListImg為刪除掉的list 使用方式
    <UploadListImg :UploadListsImg.sync="UploadListsImg"  @removeListImg="removeListImg" style="width: 400px"></UploadListImg>
    ## script
    import UploadListImg from '@/components/uploadListImg/uploadListImg.vue';
    import { Component, Vue, Model, Watch, Prop } from 'vue-property-decorator';
    @Component({
        components: {
            UploadListImg,
        }
    })
    export default class Content extends Vue {
        public UploadListsImg: object[] = [
            {
                name: 'food.jpeg',
                url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
            },
            {
                name: 'food2.jpeg',
                url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
            }
        ];
        public removeListImg: object[] = []
    }
複製程式碼

3.分頁的使用

分頁我們想要更加簡便的使用方式

// 分頁元件
<style scoped lang="scss">
    .t-pagination{
        width: 100%;
        overflow: hidden;
    }
    .t-pagination-content{
        float: right;
        margin: 20px;
    }
</style>
<template>
    <div class="t-pagination">
        <div class="t-pagination-content">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage4"
                :page-sizes="[10, 20, 30, 40, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="Paginationtotal">
            </el-pagination>
        </div>
    </div>
    
</template>

<script lang="ts">
import Utils from '@/utils/utils'
import { Component, Vue, Model, Prop, Watch } from 'vue-property-decorator';

@Component
export default class Reset extends Vue {
    // props宣告
    @Prop() private Paginationtotal!: number;
    private pageSize:number = 20;
    private currentPage4:number = 1;
    //最先開始執行
    created():void {
        if (this.$route.query.pageNum) {
            this.currentPage4 = Number(Utils.deep(this.$route.query.pageNum));
            this.pageSize = Number(Utils.deep(this.$route.query.pageSize));
        }else {
            this.currentPage4 = 1;
            this.pageSize = 20;
        }
    }
    //監聽路由變化
    @Watch('$route')
    onRouteChanged(route: any, oldRoute: any) :void {
        if (route.query.pageNum) {
            this.currentPage4 = Number(Utils.deep(route.query.pageNum))
            this.pageSize = Number(Utils.deep(route.query.pageSize));
        }else {
            this.currentPage4 = 1;
            this.pageSize = 20;
        }
        this.$forceUpdate()//強刷當前
    }
    private handleSizeChange(val:any) {
        let data:any = Utils.deep(this.$route.query);
        [data.pageNum,data.pageSize] = [1,val]
        this.start(data)
        console.log(`每頁 ${val} re條`);
    }
    private handleCurrentChange(val:any) {
        let data:any = Utils.deep(this.$route.query);
        data.pageNum = val
        data.pageSize = this.pageSize
        this.start(data)
        console.log(`當前頁: ${val}re`);
    }
    private start(ret:any) {
        this.$store.dispatch('paramsUrl',ret).then((res:any) => {
            this.$router.push(`${this.$route.path}${res}`)
        })
    }
}
</script>
# html 使用方式
<Pagination :Paginationtotal="Paginationtotal"></Pagination>
# script
import Pagination from '@/components/pagination/pagination.vue';
import { Component, Vue, Model, Watch, Provide } from 'vue-property-decorator';
@Component({
    components: {
        Pagination
    }
})
export default class Content extends Vue {
    Paginationtotal:number = 0;
}
複製程式碼

4.重製按鈕的分裝

我們重置只需要把當前的分頁重置成第一頁 20跳資料即可

// 重置按鈕
<template>
    <el-button size="mini" @click="reset(searchReserved)">重置</el-button>
</template>

<script lang="ts">
    import { Component, Vue, Model, Prop } from 'vue-property-decorator';

    @Component({
    })
    export default class Reset extends Vue {
        // props宣告 paramsUrl 為定義的當前的vuex裡面的方法
        @Prop() private searchReserved!:object
        public reset(search:any) {
            [search.pageNum,search.pageSize] = [1,20]
            this.$store.dispatch('paramsUrl',search).then((res:any) => {
                this.$router.push(`${this.$route.path}${res}`)
            })
        }
    }
</script>

## html 使用方式
<Reset :searchReserved="searchReserved"></Reset>
## script
import Reset from '@/components/reset/reset.vue';
@Component({
    components: {
        Reset
    }
})
export default class Content extends Vue {
    searchReserved = {}
}
複製程式碼

5.富文字編譯器

關於富文字編譯器,我想大家應該不陌生了,我推薦一筐tinyMce來使用到我們當前到專案裡面來富文字編譯器ts都支援還不是多,我找來很多來嘗試,最後決定用tinyMce下載一下這兩個,中間踩了很多坑,給我們伸手黨線上開箱即食的程式碼把

把cdn放上速度更快

重要的說一下我們的靜態的這個檔案放public 下面這個一定要放這,下面的這個一定要放進去不然頁面食用不了檔案連結

 ## 富文字編譯器 ## EditorContent 預設值 onChangeHandler 改變的事件 editorInit 初始配置 
 ## 基本上圖片上傳都需要form表單方式上傳  FormData
<template>
    <div>
        <Editor :initial-value="EditorContent" @onChange="onChangeHandler" id="tinyMce" :init="editorInit"></Editor>
    </div>
</template>

<script lang="ts">
    import 'tinymce/themes/modern/theme';
    import Editor from '@tinymce/tinymce-vue';
    import { Component, Vue, Model, Watch, Prop } from 'vue-property-decorator';

    @Component({
        components: {
            Editor
        }
    })
    export default class Content extends Vue {
        // 父元件傳進來的html
        @Prop(String) EditorContent: any;
        // 初始值
        public initialVal:any = '';
        public editorInit:any = {
            language_url: './static/zh_CN.js',
            language: 'zh_CN',
            selector: 'textarea',
            skin_url: './static/skins/lightgray',
            height: 300,
            // width:600,
            images_upload_url: 'https://api.uat.iyuedian.com/iyd-imall-manage/imall/v1/upload',
            plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
            toolbar: 'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat',
            images_upload_handler: function (blobInfo:any, success:any, failure:any) {
                let xhr:any, formData:any;
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', this.$store.state.imgUrl);
                xhr.onload = function() {
                    if(xhr.status<200||xhr.status>=300){
                        failure(xhr.status);
                        return;
                    }
                    let json = JSON.parse(xhr.responseText);
                    if(json.code==0){
                        success(json.data[0].newFileName);
                    } else {
                        failure('HTTP Error: ' + json.msg);
                    }
                };
                formData = new FormData();
                formData.append('file', blobInfo.blob(), blobInfo.filename());
                xhr.send(formData);
            },
            // images_upload_url: 'https://api.iyuedian.com/iyd-imall-manage/imall/v1/upload'
        }
        //最先開始執行
        created():void {
            // tinyMce.init({})
        }
        //監聽路由變化
        @Watch('$route')
        onRouteChanged(route: any, oldRoute: any) :void {
            this.$forceUpdate()
        }
        /**
         * 富文字內容變化時事件
         */
        public onChangeHandler(res:any,index:any,tag:any){
            //width height小程式不支援這個把這個替換了
            let html = res.level.content.replace("width","xxx")
            html = html.replace("height","yyy")
            // console.log(html)
            this.$emit('update:EditorContent',html)
        }
    }
</script>
## html 使用方式
<Editor :EditorContent.sync="EditorContent"></Editor>
## script
import Editor from '@/components/tinyMceEditor/tinyMceEditor.vue';
 @Component({
        components: {
            Editor
        }
    })
export default class Content extends Vue {
    // 預設圖文詳情
    public EditorContent: string = '';
}

複製程式碼

1.

使用方式

小結

基本的外掛都講了一下有問題可以新增上面的qq群