5

In the last article, we shared the relevant content of Vue3 and Vite in detail. In this article, we will take you to understand the construction of the online form system of Vite+Vue3 from the actual project.
Use Vite to initialize a Vue3 project. Note here: According to the official website documentation, using Vite requires a node version of 12 or above, please check the node version before creating a project

Initialize the project command:

 $ npm init vite-app <project-name>  // (project-name 为项目名)创建vite项目脚手架包
 $ cd <project-name>  //进入项目目录
 $ npm install  //安装项目所需依赖
 $ npm run dev  //启动项目

As an example: Build a project called myVue3.
Execute the command: npm intit vite-app myVue3

As you can see, a project has been built in the Practice folder. The project structure is as follows:

Execute the command: cd myVue3 Enter the project directory and execute the command: npm install to install the relevant modules.

The project structure is as follows: The module has been downloaded successfully.

Finally execute the command: npm run dev to start the project

Enter the address, when we see this page, the project has been successfully started.

The foreshadowing is ready, and we will officially start without saying much.

Project combat

After understanding Vue3 and Vite, let's experience it with an actual project.
Ideas:
Use SpreadJS and componentized form editor to make a simple online Excel reporting system.
The A page uses the editor to design and save the template.
Page B uses SpreadJS to import the template and fill in and upload the report.
The implementation mechanism is the data binding function of SpreadJS, you can first understand its function through the link below
https://demo.grapecity.com.cn/spreadjs/SpreadJSTutorial/features/data-binding/table-binding/purejs

The main code is as follows:
Install the required modules first

 "dependencies": {
    "vue": "^3.0.4",
    "@grapecity/spread-sheets-designer-vue": "15.1.0",
    "@grapecity/spread-sheets-designer": "15.1.0",
    "@grapecity/spread-sheets-designer-resources-cn": "15.1.0",
    "@grapecity/spread-sheets": "15.1.0",
    "@grapecity/spread-sheets-resources-zh": "15.1.0",
    "@grapecity/spread-excelio": "15.1.0",
    "@grapecity/spread-sheets-barcode": "15.1.0",
    "@grapecity/spread-sheets-charts": "15.1.0",
    "@grapecity/spread-sheets-languagepackages": "15.1.0",
    "@grapecity/spread-sheets-print": "15.1.0",
    "@grapecity/spread-sheets-pdf": "15.1.0",
    "@grapecity/spread-sheets-shapes": "15.1.0",
    "@grapecity/spread-sheets-tablesheet": "15.1.0",
    "@grapecity/spread-sheets-pivot-addon": "15.1.0",
    "@grapecity/spread-sheets-vue": "15.1.0",
    "@types/file-saver": "^2.0.1",
    "vue-router": "^4.0.0-rc.5"
  }

Run the command npm install to install all dependencies.
Next we configure routing.
1. Create a new file in the src folder.

 router/index.js

2. Configure routing

 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. Introduce in 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. Modify App.vue

 <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: {
  }
}
</script>

Careful friends may have noticed that the configuration of routing and the introduction of main.js seem to be different from the use of vue2? Yes, when using Vue Router in vue3, you need to import new methods (such as createRouter and createWebHistory) for normal use.
At the same time, the code also reflects the characteristics of the vue3 combined API. Compared with the vue2 option API (dividing the code into data, methods, etc.), vue3 defines data and methods inside the setup method, extracts business logic into functions, and returns through return, making the code logic more concise and clear.

After configuring the routing, we started to integrate the componentized form editor (Designer) and SpreadJS.

1. Integrated Designer

The code looks like this:

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

<script>

import {onMounted, ref, reactive} from "vue";
import '@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css';
import '@grapecity/spread-sheets-designer/styles/gc.spread.sheets.designer.min.css';
import "@grapecity/spread-sheets-shapes";
import '@grapecity/spread-sheets-pivot-addon';
import "@grapecity/spread-sheets-tablesheet";
import GC from '@grapecity/spread-sheets'
import "@grapecity/spread-sheets-resources-zh";
GC.Spread.Common.CultureManager.culture("zh-cn");
import "@grapecity/spread-sheets-designer-resources-cn";
import "@grapecity/spread-sheets-designer";
import {designerConfig} from '../files/config'
//import {myBudget } from '../files/budget.js';
import {myBudget} from '../files/right_demo.js';

export default {
  name: 'Designer',
  props: {
  },
  setup() {
    let designer;
    let spreadDom;
    let spread;
    onMounted(() => {
      designer = new GC.Spread.Sheets.Designer.Designer(document.getElementById("ssDesigner"), designerConfig);
      spreadDom = designer.getWorkbook().getHost();
      spread = GC.Spread.Sheets.findControl(spreadDom);
      //spread.fromJSON(myBudget);
    })
  
    return {
      designer,
      spread
    };
  }
}
</script>

<style scoped>
  
</style>

1. Add a div to the template. This div is the container of the designer. You can set the width and height of the container through CSS, that is, to customize the display size and position of the designer.
2. Import the dependencies required by the designer.
3. Initialize the designer in the setup function

As shown in the figure below, the designer has been loaded and displayed on the webpage, which means that the designer has been successfully integrated into this project.

Designer's page is similar to Excel. Using the UI buttons provided by the toolbar and the unique data binding function, we can easily implement template design.
Of course, you can also directly load the preset template through the import button or use the interface (fromJSON).

After completing the template design, click the save button to submit, here we first save the data to sessionStorage for easy access later.

Note:
The native Designer does not include a save button. We can use its powerful customization capabilities to execute relevant code logic according to business needs. The code logic of the save button is as follows:

For the complete code of the custom component, please refer to the demo at the end of the article, which will not be introduced here.
Now that Designer's integration and template design are completed, let's see how to integrate front-end form controls and fill in and collect data.

2. Integration

Similar to the integrated Designer, first create a vue page called SpreadSheet.

 <template>
  <div>
    <div>
      <button :style="{margin: '20px'}" @click="importTemplate()">导入模板</button>
      <button @click="setDataSource()">绑定数据源</button>
      <button @click="saveTemplate()">保存</button>
    </div>
    <div id="ss" 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 GC from "@grapecity/spread-sheets"
import "@grapecity/spread-sheets-resources-zh";

export default {
  name: 'SpreadSheet',
  components: {
  },
  setup(){
    let spread, sheet;
    onMounted(() => {
      let workbook = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
      let spreadDom = workbook.getHost();
      spread = GC.Spread.Sheets.findControl(spreadDom);
    });

    let importTemplate = () => {
      const json = JSON.parse(sessionStorage.getItem("templateJson"));
      spread.fromJSON(json);
    };

    let setDataSource = () => {
      sheet = spread.getActiveSheet();
      let table = sheet.tables.all()[0];
      table.allowAutoExpand(true);
      table.expandBoundRows(true);
      let data = {
          budget: [
              {item:"部门活动", Jan: 15, Feb: 25, Mar: 10, Apr: 25, May: 13, Jun: 15},
              {item:"差旅费", Jan: 15, Feb: 25, Mar: 10, Apr: 25, May: 13, Jun: 15},
              {item:"办公费", Jan: 15, Feb: 25, Mar: 10, Apr: 25, May: 13, Jun: 15},
              {item:"广告费", Jan: 15, Feb: 25, Mar: 10, Apr: 25, May: 13, Jun: 15},
              {item:"招待费", Jan: 15, Feb: 25, Mar: 10, Apr: 25, May: 13, Jun: 15}
          ]
      }
      let datasource = new GC.Spread.Sheets.Bindings.CellBindingSource(data);
      sheet.setDataSource(datasource);
    };

    let saveTemplate = () => {
      let source = sheet.getDataSource().getSource();
      sessionStorage.setItem("dataSource", JSON.stringify(source));
      console.log(source);
      alert("保存填报数据成功");
    };

    return {
      spread,
      importTemplate,
      setDataSource,
      saveTemplate
    }
  }
}
</script>

1. Add a div to the template. This div is the container of the spread. You can set the width and height of the container through CSS, that is, customize the display size and position of the spread.
2. Add import template, bind data source, save button.
3. Import the dependencies required by this component.
4. Initialize the spread in the setup method.
5. Implement the code logic corresponding to each button.

The fromJSON method is used in the importTemplate method to load the template designed by Designer.
SetDataSource uses the data binding function to bind the preset data source, or you can modify or manually fill in the report.

In the saveTemplate method, the modified/reported data source can be obtained, and the data source can be saved to the background database (in this example, it is saved to sessionStorage, which is only used as an example). The data source can be read directly from the background database when filling and reporting summary is done later.

So far, a simple online Excel reporting system has been completed. Interested partners can download the project code below and try it out for themselves.
https://gcdn.grapecity.com.cn/forum.php?mod=attachment&aid=MjIzMDM0fGIyODc2MDlmfDE2NTg4MjgyNzB8NjI2NzZ8OTk3MTg%3D

If you are interested in more examples, you can check:
https://demo.grapecity.com.cn/spreadjs/gc-sjs-samples/index.html


葡萄城技术团队
2.7k 声望29.4k 粉丝

葡萄城是专业的软件开发技术和低代码平台提供商,聚焦软件开发技术,以“赋能开发者”为使命,致力于通过表格控件、低代码和BI等各类软件开发工具和服务,一站式满足开发者需求,帮助企业提升开发效率并创新开发模式。