Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
Huawei Cloud Astro Canvas
Huawei Cloud Astro Zero
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

{widget}.js

Updated on 2025-03-24 GMT+08:00

File Introduction

{widget}.js: JavaScript file of the core rendering logic. It is loaded and executed during widget editing and page publishing and running. A recommended widget architecture should contain APIs in Table 1. Init, render, and beforeDestory are general lifecycle functions of the widget, and others are implemented by the recommended template.

Table 1 Widget architecture

API Name

API Description

Mandatory

init (lifecycle function)

Widget initialization entry API, which initializes the general capabilities of the widget and registers widget events and actions.

Yes

render (lifecycle function)

Widget core rendering API, which is used to instantiate widgets, invoke data, and implement events and actions.

Yes

beforeDestroy (lifecycle function)

Widget destroy and callback, which is used to implement the memory release logic during widget destroy. Some dom events bound to the widget and global references need to be destroyed.

Yes

initContainer

Independent logic extracted from the render, which initializes the widget container. The logic of all widgets is unified.

Unified implementation without modification.

getInitProps

The independent logic extracted from render is converged based on the default prop and the props configured for the widget, and the result is returned.

It is recommended that this function be implemented.

initI18n

Initializes the multi-language information of the widget message-en/message-zh and registers the multi-language information to an independent i18nVue instance for the widget to obtain stub data, obtain default configurations, and initialize the widget.

It is recommended that this function be implemented.

initReaderVm

Independent logic extracted from render, which is used to initialize the widget VM instance in the running state. Obtain data from the instance and implement the core rendering of the widget.

It is recommended that this function be implemented.

registerWidgetActionAndEvent

Independent logic extracted from init, which is used to register the widget events and actions.

Implemented as required and used when the widget defines events and actions.

getMockData

When a widget does not connect to an external data source, the API for obtaining stub data is used to customize the implementation. The dataset supports two-dimensional array objects. Therefore, the stub data structure is unified as the two-dimensional array object [{id:3,name:'zhangsan'}]. In some scenarios, if only a simple value val is required, you can set the widget stub data to a simple two-dimensional object array [{val:123}].

-

File Example

  • Common widget core code
    var EchartsWidgetTemplate = StudioWidgetWrapper.extend({
      /*
       * Widget initialization entry API, which initializes the general capabilities of the widget and registers widget events and actions.
       */
      init() {},
    
      /**
       * Widget core rendering API, which is used to instantiate widgets, invoke data, and implement events and actions.
       */
      render() {},
    
      /**
       * Widget destroy and callback, which is used to implement the memory release logic during widget destroy. Some dom events bound to the widget and global references need to be destroyed.
       */
      beforeDestroy() {},
    
        /**
         * Obtain widget stub data in a unified manner. It is recommended that this function be implemented.
         */
        getMockData() {},
    })
  • Overall code of the widget
    var EchartsWidgetTemplate = StudioWidgetWrapper.extend({
      /*
       * Widget initialization entry API, which initializes the general capabilities of the widget and registers widget events and actions.
       */
      init() {
        this._super.apply(this, arguments); // Construct widget common capabilities. Mandatory when the parent class constructor is called.
        this.getWidgetI18n().then(() => this.render()); // Render widget.
      },
      /**
       * Widget core rendering API, which is used to instantiate widgets, invoke data, and implement events and actions.
       */
      render() {
        const widgetContainer = this.getContainer();
        if (!widgetContainer) return;
        this.initI18n();
        this.initReaderVm(this.getProps(), widgetContainer);
        this.registerWidgetActionAndEvent();
        this.registerResizeEvent(() => this?.readerVm?.echartsInst?.resize());
      },
      /**
       * Widget destroy and callback, which is used to implement the memory release logic during widget destroy. Some dom events bound to the widget and global references need to be destroyed.
       */
      beforeDestroy() {
        $(window).off('resize');
        this.readerVm && this.readerVm.$destroy && this.readerVm.$destroy();
      },
      /**
       *
       * @returns initializes the multi-language information of the widget message-en/message-zh and registers the multi-language information to an independent i18nVue instance for the widget to obtain stub data, obtain default configurations, and initialize the widget.
       */
      initI18n() {
        const i18n = window.HttpUtils.getI18n({
          locale: window.HttpUtils.getLocale(),
          messages: this.getMessages(),
        });
        const i18nVM = new window.Vue({ i18n });
        this.$t = (key) => i18nVM.$t(key);
      },
      getProps() {
        const props = this.getProperties() || {};
        const commonProps = $.extend(
          true,
          {},
          { emphasisFocus: 'series', showLabel: true, axisPointerType: 'shadow' },
          JSON.parse(props.commonProps || '{}'),
        );
        return { commonProps };
      },
      /**
       * Used to initialize the widget VM instance in the running state.
       * @param {*} props widget configuration item
       * @param {*} widgetContainer widget container
       */
      initReaderVm(props, widgetContainer) {
        const { commonProps } = props;
        const thisObj = this;
        thisObj.readerVm = new window.Vue({
          el: $('#EchartsWidgetTemplate', widgetContainer)[0],
          data() {
            return {
              commonProps,
              dataValue: [],
              echartsInst: null,
              ConnectorIns: thisObj.getConnectorInstanceByName('EchartsWidgetTemplateConnector') || '',
            };
          },
          mounted() {
            this.echartsInst = window.echarts.init(this.$refs.echartsDom);
            this.echartsInst.on('click', 'series', (event) => {
              thisObj.triggerEvent('clickSeries', event);
            });
            thisObj.callFlowConn(this.ConnectorIns, {}, (res) => {
              this.dataValue = res;
              this.drawEcharts();
            });
          },
          methods: {
            drawEcharts() {
              const dataX = [...new Set(this.dataValue.map((row) => row.x))];
              this.echartsInst.setOption({
                xAxis: {
                  type: 'category',
                  data: dataX,
                },
                yAxis: {
                  type: 'value',
                },
                series: [...new Set(this.dataValue.map((row) => row.s))].map((key) => ({
                  data: dataX.map((x) => this.dataValue.find((item) => item.x === x && item.s === key)?.y),
                  name: key,
                  type: 'bar',
                  emphasis: { focus: this.commonProps.emphasisFocus },
                  label: {
                    show: this.commonProps.showLabel,
                    distance: this.commonProps.labelDistance,
                  },
                })),
                tooltip: {
                  trigger: 'axis',
                  axisPointer: { type: this.commonProps.axisPointerType },
                },
              });
            },
            highlightSeries({ eventParam }) {
              this.echartsInst.dispatchAction({ type: 'highlight', seriesIndex: eventParam.seriesIndex });
            },
          },
        });
      },
      /**
       * Used to register the widget events and actions.
       */
      registerWidgetActionAndEvent() {
        if (!window.Studio) {
          return;
        }
        window.Studio.registerEvents(this, 'clickSeries', { zh_CN: 'Click Series', en_US: 'Click Series' });
        window.Studio.registerAction(
          this,
          'highlightSeries',
          { zh_CN: 'Highlight Series', en_US: 'Highlight Series' },
          [],
          (...args) => this.readerVm.highlightSeries(...args),
        );
      },
      /**
       * A custom API. Stub data is used by the widget when no external data source is connected. The stub data structure is a two-dimensional array object.
       * @returns [{}]
       */
      getMockData() {
        const seviceWaterLevel = this.$t('setting.seviceWaterLevel');
        const seviceLoad = this.$t('setting.seviceLoad');
        return [
          {
            x: '00:00',
            y: 11.69,
            s: seviceWaterLevel,
          },
          {
            x: '02:30',
            y: 17.46,
            s: seviceWaterLevel,
          },
          {
            x: '05:00',
            y: 28.57,
            s: seviceWaterLevel,
          },
          {
            x: '07:30',
            y: 12.7,
            s: seviceWaterLevel,
          },
          {
            x: '10:00',
            y: 18.99,
            s: seviceWaterLevel,
          },
          {
            x: '12:30',
            y: 3.7,
            s: seviceWaterLevel,
          },
          {
            x: '15:00',
            y: 18.52,
            s: seviceWaterLevel,
          },
          {
            x: '17:30',
            y: 23.81,
            s: seviceWaterLevel,
          },
          {
            x: '20:00',
            y: 10.58,
            s: seviceWaterLevel,
          },
          {
            x: '22:30',
            y: 15.82,
            s: seviceWaterLevel,
          },
          {
            x: '24:00',
            y: 3.76,
            s: seviceWaterLevel,
          },
          {
            x: '00:00',
            y: 5.69,
            s: seviceLoad,
          },
          {
            x: '02:30',
            y: 12.46,
            s: seviceLoad,
          },
          {
            x: '05:00',
            y: 18.57,
            s: seviceLoad,
          },
          {
            x: '07:30',
            y: 25.7,
            s: seviceLoad,
          },
          {
            x: '10:00',
            y: 13.99,
            s: seviceLoad,
          },
          {
            x: '12:30',
            y: 9.7,
            s: seviceLoad,
          },
          {
            x: '15:00',
            y: 20.52,
            s: seviceLoad,
          },
          {
            x: '17:30',
            y: 28.81,
            s: seviceLoad,
          },
          {
            x: '20:00',
            y: 15.58,
            s: seviceLoad,
          },
          {
            x: '22:30',
            y: 19.82,
            s: seviceLoad,
          },
          {
            x: '24:00',
            y: 9.76,
            s: seviceLoad,
          },
        ];
      },
    });

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback