Playground instruction manual for building the OpenTiny component library

1 Knowledge background

1.1 Vue framework

A progressive framework, it is easy to learn and use, and has excellent performance. It ranks first among the three best front-end frameworks promoted in China!

1.2 OpenTiny component library

It has evolved within Huawei for 9 years and has supported the development and delivery of thousands of projects. Its set of API supports both Vue2 and Vue3 frameworks. It has more than 100 components, 6 sets of themes, supports internationalization capabilities, and supports Vite and webpack environments. Developed and built!
It is a new Vue UI component library contributed by HUAWEI CLOUD to the open source community in 2022. The code is hosted on GitHub: https://github.com/opentiny/tiny-vue. Welcome to Star and issue!
The installation package is released In the Npm public warehouse and Huawei's internal central warehouse, it complies with the MIT open source agreement, and everyone can freely install and use it!
Opentiny component library official website documentation: https://opentiny.design/tiny-vue

image.png
Figure 1 Opentiny introduction

1.3 playground of component library

The Playground application is actually a real-time component preview page. For example, the Vue official website provides the function of "Vue Playground", link: https://play.vuejs.org/ , which conveniently provides a minimal Vue environment that can Let users try to write some Vue code, and see the real-time preview results!

Build 2.png
Figure 2 Vue official playground renderings

It supports multiple files, supports Import Map the introduction of third-party component scripts, supports real-time editing of code, real-time compilation, preview and code sharing! The playground of the component library is to build an application page, which can preview the components of a certain component library in real time, through which you can quickly understand and try each component!

Vue's official open source Playground component—@vue/repl, reference document: https://github.com/vuejs/repl#readme .

2 Guidance on how to build a playground for the OpenTiny component library

Today's content is: build a drill field for the OpenTiny component library. This task requires you to be familiar with the front end and have experience in Vue project development. The finished rendering is as follows:

Build 3.png
Figure 3 Schematic diagram of the challenge task

Please refer to the following steps to complete this task:

2.1 Create a new project and install dependent packages

Install nodejs 16+, vscode and other front-end tools, and then use vite to create a vue javascript project!

npm create vite@latest   

Then install the Playground components and the dependencies of the opentiny/vue components

npm install  @vue/repl @opentiny/vue@3 

And be sure to refer to the installation documentation of opentiny/vue, https://opentiny.design/tiny-vue/zh-CN/os-theme/docs/installation to configure the project.
At present, everyone already has a standard vue project. After npm install, you can npm run dev to start and see a vue sample project.

Build 4.png
Figure 4 Vue's new project initial page

2.2 Create the page structure and introduce the required variables

Next, delete HelloWorld.vue. In main.js, remove the style.css reference. We only complete all functions in App.vue! The page structure of App.vue is as follows:

<script setup>
import {
      
       reactive } from 'vue';
import {
      
       Repl, ReplStore, File } from '@vue/repl'
import CodeMirror from '@vue/repl/codemirror-editor'
import '@vue/repl/dist/style.css'

import {
      
       Switch as TinySwitch, ButtonGroup as TinyButtonGroup, Select as TinySelect, Option as TinyOption, Modal } from '@opentiny/vue'
import {
      
       IconShare as TinyIconShare } from "@opentiny/vue-icon"

// 将在此处补充逻辑代码

</script>

<template>

<div>将在此处补充模板代码</div>
 
</template>

<style>
 * {
      
        box-sizing: border-box;}
.header {
      
      
  height: 36px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-bottom: 6px;
  border-bottom: solid 1px #e1e1e1;
}
.vue-repl {
      
        height: calc(100vh - 36px - 16px) !important;}
.header > div {
      
        vertical-align: middle;}
.title {
      
        font-size: 20px;}
.ml20 {
      
        margin-left: 20px;}
</style>

2.3 Develop top functions

The application template is divided into upper and lower parts, the upper part is the title Logo and a set of selection functions and sharing buttons! The following part is a <Repl>component. Let's develop the top function first, its <template>code is as follows:

<div class="header">
    <div class="title">
      <img src="./assets/opentiny-logo.svg" /> <span>OpenTiny Vue 演练场</span>
    </div>
    <div>
      <span class="ml20">
        显示编译输出: <tiny-switch v-model="state.showCompileOutput" />
      </span>
      <span class="ml20">
        显示ImportMap: <tiny-switch v-model="state.showImportMap" />
      </span>
      <span class="ml20">
        布局方向: <tiny-button-group :data="state.layoutOptions" v-model="state.layout"></tiny-button-group>
      </span>
      <span class="ml20">
        版本: <tiny-select v-model="state.selectVersion" style="width:150px">
          <tiny-option v-for="item in state.versions" :key="item.value" :label="'opentiny/vue@' + item.value"
            :value="item.value">
          </tiny-option>
        </tiny-select>
      </span>
      <icon-share style="font-size: 16px;margin:0 20px; cursor: pointer;" />
    </div>
  </div>

A set of data and methods have been bound in the template. Next, we need to add these contents to <script>the section.

const iconShare = TinyIconShare()

const state = reactive({
    
    
  // repl 属性
  showCompileOutput: true,
  showImportMap: true,
  layout: 'horizon',
  layoutOptions: [{
    
     value: 'horizon', text: "水平" }, {
    
     value: 'vertical', text: "垂直" }],
  // 版本切换
  versions: [{
    
     value: "3.8.0" }, {
    
     value: "3.8.1" }, {
    
     value: "3.8.2" }, {
    
     value: "3.8.3" }, {
    
     value: "3.8.4" }],
  selectVersion: "3.8.4"
})

At this point, we should be able to get the following application. The top display switch and layout direction are bound to 3 variables, but the version selection and sharing functions have not been developed yet!

Build 5.png
Figure 5 top function renderings

★ After this step, we have learned how to use @opentiny/vue components easily!

2.4 Develop <Repl>components to realize script preview

First, in the template, introduce the Repl tag, and bind the previous 3 variables and the ReplStore variable. Add the following tags below the header structure:

  <Repl :store="store" :editor="CodeMirror" :show-compile-output="state.showCompileOutput" :show-import-map="state.showImportMap"
    :previewOptions="state.previewOptions" :clear-console="false" :layout="state.layout"></Repl>

The store variable and state.previewOptions are used here, so in <script>the section, add these 2 variables:

// repl组件需要store管理状态
const store = new ReplStore({
    
    
  showOutput: true,
  outputMode: "preview"
});

const state = reactive({
    
    
  // 加入这一句
    previewOptions: {
    
     headHTML: '' },
})

At this point, we get a prototype of a playground that can be linked: write code on the right, real-time preview on the left, operate the functions on the top, and the area responds. The interface is as follows:

Build 6.png

Figure 6 component renderings

★ After this step, we have learned how to use the components!

2.5 Realize switching version

To switch versions is to switch the importMap script referenced by the repl component to achieve a dynamically switched @opentiny/vueversion. Currently it has released 5 versions including 3.8.0~3.8.4! In <script>, add the following script:

const createImportMap = (version) => {
    
    
  return {
    
    
    imports: {
    
    
      "@opentiny/vue": `https://unpkg.com/@opentiny/vue@${
      
      version}/runtime/tiny-vue.mjs`,
      "@opentiny/vue-icon": `https://unpkg.com/@opentiny/vue@${
      
      version}/runtime/tiny-vue-icon.mjs`,
      "@opentiny/vue-locale": `https://unpkg.com/@opentiny/vue@${
      
      version}/runtime/tiny-vue-locale.mjs`,
      "@opentiny/vue-common": `https://unpkg.com/@opentiny/vue@${
      
      version}/runtime/tiny-vue-common.mjs`
    }
  }
};

function versionChange(version) {
    
    
  const importMap = createImportMap(version)
  store.setImportMap(importMap);
  state.previewOptions.headHTML = `<link rel="stylesheet" href="https://unpkg.com/@opentiny/vue-theme@${
      
      version}/index.css">`
}

We wrote the versionChange function and bound it to the change event of the previous template, so that after the drop-down changes, the store will be notified to set a new importMap address!
Now after switching the version, you can see through the developer tool that it will immediately request each runtime script package of the corresponding version of @opentiny/vue.

★ After this step, we have learned the event binding of the Tiny-Select component and setting the importMap variable of the store!

2.6 Realize code sharing

The Repl component supports code sharing. Its principle is: the store object serializes the internal state into base64 encoding, and puts it in the hash of the url to share with others. When the page is loaded, if you find that the hash has content, you will know that this is the state of the store, pass it to the store, and the store will deserialize it internally.
When we share the application, we need to record the component library version number and store status, so we plan to use hash to save the version and base64 value at the same time: 3.8.4|eNqIVV9p…

const hash = location.hash.slice(1)
// shareData数组如果有2项,则表明是分享链接,否则是非分享页面
const shareData = hash.split('|')

const store = new ReplStore({
    
    
  // 添加下面一行
  serializedState: shareData.length == 2 ? shareData[1] : '',
  showOutput: true,
  outputMode: "preview"
});

const state = reactive({
    
    
  // 修改下面这一行
  selectVersion: shareData.length == 2 ? shareData[0] : "3.8.4"
})

// 分享链接和非分享链接的逻辑不同,此处判断一下
if (shareData.length == 2) {
    
    
  versionChange(shareData[0])
} else {
    
    
  versionChange('3.8.4')
}

// 生成分享链接
function share() {
    
    
  const hash = store.serialize().slice(1)
  const shareUrl = location.origin + '#' + state.selectVersion + '|' + hash

  navigator.clipboard.writeText(shareUrl);
  Modal.alert(`已复制分享链接`, '分享成功')
}

Bind the share function to the click event of the share icon in the template, so that clicking the icon will copy the link to the clipboard, and then open a new tab to access the share link.
In the new page opened in the share link, the current hash has a very long string, so that shareData is parsed to the serialized value of the version and store, so the content of shareData[1] is assigned to the store, and this is achieved The sharing function is enabled, try to see if it works!

★ After this step, we have learned the design of the sharing function and the serialization of the store!

2.7 Test @opentiny/vue component library

The following is an example of using the @opentiny/vue component library, copy it to the application window, and modify the script to verify that the function is correct. Click the share button and copy to other tabs to see if the content is shared.

<script setup>
import {
      
       reactive } from "vue"
import {
      
       Button as TinyButton, Alert as TinyAlert, Numeric as TinyNumeric, Slider as TinySlider, Select as TinySelect, Option as TinyOption, Modal } from "@opentiny/vue"

const state = reactive({
      
      
  value: 42,
  selectValue: "",
  options: [
    {
      
       value: '选项1', label: '黄金糕' },
    {
      
       value: '选项2', label: '双皮奶' },
    {
      
       value: '选项3', label: '蚵仔煎' },
    {
      
       value: '选项4', label: '龙须面' },
    {
      
       value: '选项5', label: '北京烤鸭' }
  ],
})

function showValue() {
      
      
  Modal.alert(`当前值: ${ 
        state.value} \n 当前下拉框值: ${ 
        state.selectValue}`, '标题')
}
</script>
<template>
  <div class="mb20">Alert 演示</div>
  <div class="mb20">
    <tiny-alert description="type 为默认值 success"></tiny-alert>
    <tiny-alert type="error" description="type 为 error"></tiny-alert>
    <tiny-alert type="info" description="type 为 info"></tiny-alert>
    <tiny-alert type="warning" description="type 为 warning"></tiny-alert>
  </div>
  <div class="mb20">组件 演示</div>
  <div class="mb20">
    <tiny-numeric v-model="state.value"></tiny-numeric>
    <tiny-slider v-model="state.value"></tiny-slider>
    下拉选择框:<tiny-select v-model="state.selectValue" placeholder="请选择">
      <tiny-option v-for="item in state.options" :key="item.value" :label="item.label" :value="item.value"> </tiny-option>
    </tiny-select>
  </div>
  <div>
    <tiny-button @click="showValue">显示当前值</tiny-button>
  </div>
</template>

<style>
div .tiny-select {
      
      
  width: 200px;
}

.mb20 {
      
      
  margin-bottom: 20px;
}
</style>

About OpenTiny

OpenTiny is an enterprise-level component library solution produced by HUAWEI CLOUD. It adapts to multiple terminals such as PC/mobile, covers Vue2/Vue3/Angular multi-technology stacks, and has efficiency improvements such as theme configuration system/middle-background template/CLI command line Tools that help developers efficiently develop web applications.

Core highlights:

  1. 跨端跨框架: Using the Renderless non-rendering component design architecture, a set of codes supports Vue2/Vue3, PC/Mobile at the same time, and supports function-level logic customization and full template replacement, with good flexibility and strong secondary development capabilities.
  2. 组件丰富: There are 80+ components on the PC side and 30+ components on the mobile side, including high-frequency components Table, Tree, Select, etc., with built-in virtual scrolling to ensure a smooth experience in big data scenarios. In addition to common components in the industry, we also provide Some unique feature components, such as: Split panel divider, IpAddress IP address input box, Calendar calendar, Crop image cropping, etc.
  3. 配置式组件: The component supports both template and configuration methods, suitable for low-code platforms. Currently, the team has integrated OpenTiny into the internal low-code platform, and has made a lot of optimizations for low-code platforms
  4. 周边生态齐全: Provides a TinyNG component library based on Angular + TypeScript, a TinyPro mid-background template with 10+ practical functions and 20+ typical pages, a TinyCLI engineering tool covering the entire process of front-end development, and a powerful online theme configuration platform TinyTheme

contact us:

Guess you like

Origin blog.csdn.net/OpenTiny/article/details/131900322