首页 > 其他分享 >StencilJs学习之组件装饰器

StencilJs学习之组件装饰器

时间:2023-06-19 16:57:29浏览次数:44  
标签:StencilJs Component class Watch Prop State boolean 组件 装饰

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 装饰器将在下一节 事件 中讲解。

标签:StencilJs,Component,class,Watch,Prop,State,boolean,组件,装饰
From: https://www.cnblogs.com/guojikun/p/17491469.html

相关文章

  • Python3使用装饰器实现参数类型检查
    fromfunctoolsimportwrapsdefmerge_args(varnames:tuple,args:tuple,kwargs:dict)->dict:"""融合参数-将args参数都转为kwargs参数:paramvarnames:变量名列表:paramargs:args参数:paramkwargs:kwargs参数:return:"&......
  • (四)Boot组件
       ......
  • 你曾遇到的某大厂奇葩问题:Android组件化开发,组件间的Activity页面跳转
    组件化开发有什么好处?1、当项目越来越大时,app的业务越来越复杂,会出现业务功能复杂混乱,各功能块、页面相互依赖,相互调用太多导致耦合度高,而采用组件化开发,我们就可以将功能模块合理的划分,降低功能耦合度。2、不采用组件化开发时,编译速度缓慢,修改一个页面布局编译一下还得等几分钟。......
  • Jetpack组件库(含Jetpack Compose)从入门到精通全家桶【附Demo】
    前言开发应用程序就像搭积木。我们对产品业务及功能模块的划分和封装,就像在搭建积木一样。积木不能太大,这不利于修改和拆解;积木也不能太小,否则管理起来可能会很混乱。只有基于稳健、合理的架构,项目才能轻松应对需求的变化,才有可能健康成长。没有良好架构的应用程序,就像没有搭好底......
  • Tab切换以及倒计时组件封装
    1、Tab组件功能支持默认选中tab子元素可以是文本或者图片自定义tab的数量,并自适应展示实现方式用ul>li标签遍历传入的tabs数组参数渲染判断是否传入背景,未传则显示文字绑定点击事件特点简单易用可适配性2、倒计时组件功能常用于榜单或者活动结束倒计时......
  • 得到、微信、美团、爱奇艺APP组件化架构实践
    一、背景随着项目逐渐扩展,业务功能越来越多,代码量越来越多,开发人员数量也越来越多。此过程中,你是否有过以下烦恼?项目模块多且复杂,编译一次要5分钟甚至10分钟?太慢不能忍?改了一行代码或只调了一点UI,就要run整个项目,再忍受一次10分钟?合代码经常发生冲突?很烦?被人偷偷改了自己模块的代......
  • Android组件开发简介
    一、背景一个app随着业务增加,代码放在同一个模块中会越来越臃肿,同时也导致多人开发的一个难度。组件化可以把业务单独分出来,形成一个单独模块,可单独运行、测试等,相互之间不会影响。另外一个优势,如果一个公司有多个app,总会出现一些相同业务,如登录/注册。我们可以单独把公共业务封装......
  • 前端Vue图片上传组件支持单个文件多个文件上传 自定义上传数量 预览删除图片 图片压缩
    前端Vue图片上传组件支持单个文件多个文件上传自定义上传数量预览删除图片图片压缩,下载完整代码请访问uni-app插件市场址:https://ext.dcloud.net.cn/plugin?id=13099效果图如下:1.0.0(2023-06-18)组件初始化使用方法<!--count:最大上传数量 imageList:图片上传选......
  • 微服务中「组件」集成
    目录一、简介二、缓存管理三、消息队列四、搜索引擎五、定时任务六、数据存储七、参考源码有品:Thereisnosilverbullet;一、简介在微服务工程的技术选型中,会涉及到很多组件的集成,最常用包括:缓存、消息队列、搜索、定时任务、存储等几个方面;如果工程是单服务,对于集成组件的......
  • springboot启动流程 (2) 组件扫描
    SpringBoot的组件扫描是基于Spring@ComponentScan注解实现的,该注解使用basePackages和basePackageClasses配置扫描的包,如果未配置这两个参数,Spring将扫描该配置类所属包下面的组件。在服务启动时,将使用ConfigurationClassPostProcessor扫描当前所有的BeanDefinition,解析Configur......