StencilJs學習之組件裝飾器

来源:https://www.cnblogs.com/guojikun/archive/2023/06/19/17491469.html
-Advertisement-
Play Games

stenciljs 可以方便的構建互動式組件 支持以下裝飾器 - component - state - prop - watch - method - element - event - listen ## Component 裝飾器 `@Component` 是一個裝飾器,它將 TypeScri ...


stenciljs 可以方便的構建互動式組件
支持以下裝飾器

  • component
  • state
  • prop
  • watch
  • method
  • element
  • event
  • listen

Component 裝飾器

@Component 是一個裝飾器,它將 TypeScript 類指定為 Stencil 組件。 每個模板組件在構建時都會轉換為 Web component。

import { Component } from '@stencil/core';

@Component({
  tag: 'todo-list',
  styleUrl: './todo-list.css',
  // additional options
})
export class TodoList {
  // implementation omitted
}

@Component裝飾器還有其它的一些參數

  • assetsDirs: 是從組件到包含組件所需的靜態文件(資產)的目錄的相對路徑數組。
  • scope:是否隔離css的作用域,如果啟用了shadow則此項不能設置為 true
  • shadow: 陰影dom用來隔離樣式。
  • styleUrls:包含要應用於組件的樣式的外部樣式表的相對 URL 列表。
  • styles:內聯 CSS 而不是使用外部樣式表的字元串。

State

@State 用於內部的狀態管理,修改 @State裝飾的變數會觸發組件的重新渲染

import { Component, State, h } from '@stencil/core';

@Component({
    tag: 'current-time',
})
export class CurrentTime {
    timer: number;

    // `currentTime` is decorated with `@State()`,
    // as we need to trigger a rerender when its
    // value changes to show the latest time
    @State() currentTime: number = Date.now();
    
    connectedCallback() {
        this.timer = window.setInterval(() => {            
            // the assignment to `this.currentTime`
            // will trigger a re-render
            this.currentTime = Date.now();
        }, 1000);
    }

    disconnectedCallback() {
        window.clearInterval(this.timer);
    }

    render() {
        const time = new Date(this.currentTime).toLocaleTimeString();

        return (
            <span>{time}</span>
        );
    }
}

Prop

@Prop 是用於聲明外部數據傳入組件的裝飾器。

支持的數據類型有 number string boolean Object array,可以
使用this 進行數據訪問,在html 設置需要使用dash-case 方式
在jsx 中使用camelCase 方式,預設prop 是不可變的,使用添加
mutable: true 進行修改, 使用 reflech 可以保持 prophtml屬性 同步

import { Component, Prop, h } from '@stencil/core';

@Component({
    tag: 'todo-list-item',
})
export class ToDoListItem {
    @Prop({
        mutable: true,
        reflect: false
    }) isComplete: boolean = false;
    @Prop({ reflect: true }) timesCompletedInPast: number = 2;
    @Prop({ reflect: true }) thingToDo: string = "Read Reflect Section of Stencil Docs";
}

Watch

@Watch()是應用於模具組件方法的修飾器。 修飾器接受單個參數,即用 @Prop()@State() 修飾的類成員的名稱。 用 @Watch() 修飾的方法將在其關聯的類成員更改時自動運行。

// We import Prop & State to show how `@Watch()` can be used on
// class members decorated with either `@Prop()` or `@State()`
import { Component, Prop, State, Watch } from '@stencil/core';

@Component({
  tag: 'loading-indicator' 
})
export class LoadingIndicator {
  // We decorate a class member with @Prop() so that we
  // can apply @Watch()
  @Prop() activated: boolean;
  // We decorate a class member with @State() so that we
  // can apply @Watch()
  @State() busy: boolean;

  // Apply @Watch() for the component's `activated` member.
  // Whenever `activated` changes, this method will fire.
  @Watch('activated')
  watchPropHandler(newValue: boolean, oldValue: boolean) {
    console.log('The old value of activated is: ', oldValue);
    console.log('The new value of activated is: ', newValue);
  }

  // Apply @Watch() for the component's `busy` member.
  // Whenever `busy` changes, this method will fire.
  @Watch('busy')
  watchStateHandler(newValue: boolean, oldValue: boolean) {
    console.log('The old value of busy is: ', oldValue);
    console.log('The new value of busy is: ', newValue);
  }
  
  @Watch('activated')
  @Watch('busy')
  watchMultiple(newValue: boolean, oldValue: boolean, propName:string) {
    console.log(`The new value of ${propName} is: `, newValue);
  }
}

mehtod

可以方便的導出函數,方便外部調用。

import { Method } from '@stencil/core';

export class TodoList {

  @Method()
  async showPrompt() {
    // show a prompt
  }
}

// used registered
el.showPrompt();

Element

@Element 裝飾器是如何訪問類實例中的 host 元素。這將返回一個 HTMLElement 實例,因此可以在此處使用標準 DOM 方法/事件。

import { Element } from '@stencil/core';

...
export class TodoList {

  @Element() el: HTMLElement;

  getListHeight(): number {
    return this.el.getBoundingClientRect().height;
  }
}

其它

Event 和 Listen 裝飾器將在下一節 事件 中講解。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Linux安裝MongoDB 4.0.3 1.準備 CentOS下安裝MongoDB 官網提供windows、Linux、OSX系統環境下的安裝包,這裡主要是記錄一下在Linux下的安裝。首先到官網下載安裝包。文中安裝的是4.0.3版本的。 官網地址:https://www.mongodb.com/ ...
  • 近日,華為全球智慧金融峰會2023在上海順利舉行,華為雲副總裁、戰略與產業發展部總裁黃瑾發表了《做強堅實數據底座,GaussDB與產業攜手共進》的主題演講。 以下為演講實錄: 尊敬的各位來賓,大家下午好!非常高興和大家探討關於做堅實數據底座,GaussDB與產業攜手共進的一些思考。 中國資料庫市場發 ...
  • #報錯信息: ``` ****: 第4 行附近出現錯誤: 不是 GROUP BY 表達式 ``` #修改辦法: ######達夢可以配置相容參數,COMPATIBLE_MODE=4,靜態參數,需要重啟資料庫後生效! ``` sp_set_para_value(2,'COMPATIBLE_MODE', ...
  • 本文主要測試驗證 Elasticsearch 各版本快照在 [Easysearch](https://www.infinilabs.com/docs/latest/easysearch/overview) 中進行數據恢復。 ## 準備測試數據 ### 索引 ![](https://www.infin ...
  • # 一、Android程式員需要具備的素養 1. 應該熱愛學習Android知識 2. 具備基本的自學能力和解決問題的能力 3. 具備實踐能力 # 二、Android程式員最終需要熟練掌握的語言 1. Java(基本) 2. C/C++(進階) 3. Kotlin(基本) 4. Python(可選) ...
  • Airtest是一個跨平臺的、基於圖像識別的UI自動化測試框架,適用於游戲和App,支持平臺有Windows、Android和iOS。Airtest框架基於一種圖形腳本語言Sikuli,引用該框架後,不再需要一行行的寫代碼,通過截取按鈕或輸入框的圖片,用圖片組成測試場景,這種方式學習成本低,簡單易上... ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 按需導入的配置文件 配置文件這裡就不再贅述,內容都是一樣的,主打一個隨用隨取,按需導入。 import * as echarts from "echarts/core"; // 引入用到的圖表 import { LineChart, ty ...
  • 問題: setRules時,uview提示:設置rules,model必須設置 原因: <u-form ref="form1" v-model="model1">眼瞎把v-model當成:model,可能全網只有我遇到。 解決: <u-form ref="form1" :model="model1" ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...