Vue 3 組件開發:搭建基於 Vite 的在線表格編輯系統(組件集成)

通過前文的學習,我們已經用 Vite 搭建出了Vue 3 的項目原型。今天,我們將基於這個原型,集成 SpreadJS 電子表格組件和在線編輯器組件,使其具備 Excel公式計算、在線導入導出 Excel 文檔、數據透視表和可視化分析能力,實現在線表格編輯系統的雛形。

設計思路

· 同時創建SpreadJS 和Designer(表格編輯器)兩個組件,用切換路由的方式顯示不同組件類型。

· 在編輯器組件的工具欄中增加“加載”和“更新”兩個按鈕。

· 點擊“加載”即可加載從服務器獲取的Excel文件,在編輯器中對該組件做一些修改,點擊“更新”按鈕,將修改後的文件傳遞給服務器。

· 切換路由顯示 SpreadJS 組件,在該組件添加 “加載”和“更新”兩個button,功能同上。

SpreadJS 組件介紹

SpreadJS是一款基於 HTML5 的原生JavaScript組件,兼容 450 種以上的 Excel 公式,提供高度類似 Excel 的功能,主要用於開發 Web Excel 組件,實現多人協同編輯、高性能模板設計和數據填報等功能模塊,組件架構符合UMD規範,可以以原生的方式嵌入各類應用,並與前後端技術框架相結合。

image.png

目前,SpreadJS已針對Vue 2做了組件封裝,暫時還未對Vue 3提供組件封裝,不過我們可以通過自己封裝SpreadJS組件和表格編輯器的方式,將其集成在Vue 3項目中。

將 SpreadJS 與Vue 3 集成

1. 安裝模塊

修改package.json 文件,添加我們需要的模塊,運行命令 npm install 來安裝所有依賴項目。


"dependencies": {

    "@fortawesome/fontawesome-free": "^5.14.0",

    "@grapecity/spread-excelio": "^14.0.1",

    "@grapecity/spread-sheets": "^14.0.1",

    "@grapecity/spread-sheets-barcode": "^14.0.1",

    "@grapecity/spread-sheets-charts": "^14.0.1",

    "@grapecity/spread-sheets-designer": "^14.0.1",

    "@grapecity/spread-sheets-designer-resources-cn": "^14.0.1",

    "@grapecity/spread-sheets-designer-vue": "^14.0.1",

    "@grapecity/spread-sheets-languagepackages": "^14.0.1",

    "@grapecity/spread-sheets-pdf": "^14.0.1",

    "@grapecity/spread-sheets-pivot-addon": "^14.0.1",

    "@grapecity/spread-sheets-print": "^14.0.1",

    "@grapecity/spread-sheets-resources-zh": "^14.0.1",

    "@grapecity/spread-sheets-shapes": "^14.0.1",

    "@grapecity/spread-sheets-vue": "^14.0.1",

    "axios": "^0.21.0",

    "vue": "^3.0.2",

    "vue-router": "^4.0.0-rc.5"

  },

2. 配置路由

在src文件夾下添加3個文件。

· router/index.js

· views/SpreadSheet.vue

· views/Designer.vue

配置路由:


import { createRouter, createWebHistory } from "vue-router";

const routes = [

  {

    path: "/",

    name: "Designer",

    component: () => import("../views/Designer.vue"),

  },

  {

    path: "/spreadSheet",

    name: "SpreadSheet",

    component: () => import("../views/SpreadSheet.vue"),

  }

];

export const router = createRouter({

  history: createWebHistory(),

  routes:routes

});

3. 在main.js中引入:


import { createApp } from 'vue'

import { router } from './router/index'

import App from './App.vue'

import './index.css'

const app = createApp(App)

app.use(router);

app.mount('#app')

4. 修改App.vue:

在main.js文件中,將 Vue Router 文件添加到項目中(在Vue 2 中,導入它使用的是 Vue.use(router) ,但在Vue 3中添加方式發生了變化)。如下面的截圖所示,Vue 3是使用createApp方法來實際創建項目的,在掛載應用程序前,需要通過  app.use(router)  來添加到項目中。


<template>

<div id="app">

    <div>

        <router-link to="/">Designer</router-link> |

        <router-link to="/spreadSheet">SpreadSheet</router-link>

    </div>

  <router-view/>

</div>

</template>

<script>

export default {

  name: 'App',

  components: {

  },

  setup(){

  }

}

</script>

看到這裏大家應該會發現,Vite中的路由配置以及 main.js 引入的方式較Vue 2有所不同,爲了讓其更好的支持Typescript,Vue Router的Vue 3版本要求我們必須導入新方法才能使代碼正常工作,其中最重要的是createRouter 和 createWebHistory。

5. 集成designer組件

配置完路由之後,就可以開始集成designer組件了。首先,在components文件夾下添加2個文件:

· components/Designer.vue

· components /SpreadSheet.vue

接着,在 Designer.vue 中集成SpreadJS 表格編輯器,代碼如下圖所示:

· 在模板中添加一個div,這個div就是編輯器的容器,可以通過css設置容器的寬高位置等,也就是自定義了編輯器的顯示大小及位置。

· 導入編輯器所需要的依賴。

· 在setup函數中新建一個編輯器。


<template>

  <div>

      <div ref="ssDesigner" style="height:700px;width:100%;text-align: left;"></div>

  </div>

</template>

<script>

import { onMounted, ref} from "vue";

import "../../node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css";

import "../../node_modules/@grapecity/spread-sheets-designer/styles/gc.spread.sheets.designer.min.css";

import "@grapecity/spread-sheets-designer-resources-cn";

import "@grapecity/spread-sheets-designer";

import GC from '@grapecity/spread-sheets'

import ExcelIO from '@grapecity/spread-excelio'

export default {

  name: 'Designer',

  props: {

  },

  setup(props, {emit}) {

    const ssDesigner = ref(null);

    onMounted(() => {

      var designer = new GC.Spread.Sheets.Designer.Designer(ssDesigner.value);

      emit("designerInitialized", designer);

    });

    return {

      ssDesigner

    };

  }

}

</script>

第三步,在views/Designer.vue中引入該組件及相關依賴。


import Designer from '../components/Designer.vue'

import {ref} from "vue"

import axios from "axios"

import GC from '@grapecity/spread-sheets'

import ExcelIO from '@grapecity/spread-excelio'

第四步,在模板中使用該組件標籤。


<template>

  <div>

    <Designer v-on:designerInitialized="designerInitialized"></Designer>

  </div>

</template>

最後,在setup函數中初始化編輯器。


let designer = undefined;

let designerInitialized=(wb)=>{

      designer = wb;

      let spread = designer.getWorkbook();

    }

完成上述步驟,頁面就可以顯示編輯器UI了。

如何自定義編輯器的工具欄?

完成了上述步驟,我們已經成功的將 SpreadJS編輯器集成到項目中,接下來演示如何在工具欄中新建 “加載”和“更新”兩個按鈕。

由於 SpreadJS  在線表格編輯器採用了全新可配置設計,在任何區域都可採取json config 的配置方式。通過修改默認的GC.Spread.Sheets.Designer.DefaultConfig,便可以達到自定製功能。

1. 定製 Ribbon 選項卡

在瀏覽器Console中輸入GC.Spread.Sheets.Designer.DefaultConfig可查看默認ribbon選項卡配置。參考默認配置,可以自定義操作選項卡。


let DefaultConfig = GC.Spread.Sheets.Designer.DefaultConfig;

let customerRibbon = {

      id: "operate",

      text: "操作",

      buttonGroups: [

      ],

};

2、自定義按鈕

在定義按鈕之前,需要先定義按鈕點擊時的命令Commands,並將命令註冊到config的commandMap屬性上。


let ribbonFileCommands = {

        "loadTemplateCommand": {

            iconClass: "ribbon-button-download",

            text: "加載",

            //bigButton: true,

            commandName: "loadTemplate",

            execute: load

        },

        "updateTemplateCommand": {

            iconClass: "ribbon-button-upload",

            text: "更新",

            //bigButton: true,

            commandName: "updateTemplate",

            execute: update

        }

    }

上面的示例代碼註冊了 loadTemplateCommand和 updateTemplateCommand 兩個命令。

· execute對應具體執行內容的function,也就是 load 和 update 方法。

· iconClass爲按鈕樣式,可以制定按鈕圖片

· text爲按鈕顯示文字

· commandName爲命令名稱,需要全局唯一

iconClass示例代碼:


.ribbon-button-download {

 background-image: url(圖片地址,可以是base64 svg)};

有了命令就可以添加對應button 的config了:


let customerRibbon = {

      id: "operate",

      text: "操作",

      buttonGroups: [

        {

          label: "文件操作",

          thumbnailClass: "ribbon-thumbnail-spreadsettings",

          commandGroup: {

            children: [

              {

                direction: "vertical",

                commands: ["loadTemplateCommand", "updateTemplateCommand"],

              }

            ],

          },

        },

      ],

    };

在designer的config中加入自定義的命令和按鈕:


DefaultConfig.ribbon.push(customerRibbon);

    DefaultConfig.commandMap = {};

    Object.assign(DefaultConfig.commandMap, ribbonFileCommands);

最後,不要忘了補充Load方法和update方法中的代碼。

Load方法和update方法的作用

Load方法用於執行excel文件的加載。在接收到後臺傳遞的json數據後,使用fromJSON方法加載該文件,代碼如下圖:


let load = (e)=>{

        let spread = designer.getWorkbook();

        let formData = new FormData();

        formData.append("fileName", "path");

        axios.post('spread/loadTemplate', formData, {

            responseType: "json",

        }).then((response) => {

            if(response) {

                alert("加載成功");

                templateJSON = response.data;

                spread.fromJSON(templateJSON);

            }

        }).catch((response) => {

            alert("錯誤");

        })

}

Update方法用於執行文件的更新。在編輯器對加載的文件做出操作,如修改背景色、添加文本時,使用toJSON方法將當前spread保存爲json數據傳遞給後臺存儲,代碼如下:


let update = (e)=>{

        let spread = designer.getWorkbook();

        let spreadJSON = JSON.stringify(spread.toJSON());

        let formData = new FormData();

        formData.append("jsonString", spreadJSON);

        formData.append("fileName", "fileName");

        axios.post('spread/updateTemplate', formData).then((response) => {

            if(response) {

                alert("更新成功");

            }

        }).catch((response) => {

            alert("錯誤");

        })

    }

完成上述操作,新建的按鈕就可以正常工作了。如下圖示例,點擊工具欄加載按鈕,文件已在 SpreadJS 表格編輯器成功加載。

image.png

以上就是Vue 3 組件開發:搭建基於SpreadJS的表格編輯系統(組件集成篇)的全部內容,通過集成 SpreadJS 電子表格組件和在線編輯器組件,我們搭建的項目原型已經具備了在線表格編輯系統的雛形。

在下一章功能拓展篇中,我們將演示如何爲這個系統雛形增加更多電子表格功能,並提供整個工程源碼供參考。

擴展閱讀

· Vue 3 組件開發實戰:搭建基於SpreadJS的表格編輯系統(環境搭建篇)

· Vue 3 組件開發實戰:搭建基於SpreadJS的表格編輯系統(功能拓展篇)

· SpreadJS Vue 框架支持

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章