【问题标题】:Aurelia Component. Is there a way to access a function of a component in typescriptAurelia 组件。有没有办法在打字稿中访问组件的功能
【发布时间】:2016-08-03 10:03:50
【问题描述】:

有没有办法从一个视图中调用组件函数?有点像。

我正在寻找一种方法来从我的ViewPage 调用组件上的show() 函数。

组件

//component.html 
<template>
    <div id="sidebar"></div>
</template>

// component.css 
#sidebar {
    display: none;
}

// component.ts
import {bindable} from 'aurelia-framework';

export class Sidebar {

    @bindable data: Array<string>;

    show = () : void => {
        // Shows this specific side bar
    }

    hide = () : void => {
        // Hides this specific side bar
    }
}

查看

// view.html 
<template>
    <require from="./sidebar"></require>
    <sidebar data.bind="data"></sidebar>
    <button click.delegate="showSidebar()"></button>
<template>

// view.ts
export class ViewPage {

    data: Array<string> = ["Hello", "I", "Am", "Sidebar", "Content"];

    showSidebar = () : void => {
        // how to show the side bar component here?? 
        // I need something like sidebar.show();?
    }
}

【问题讨论】:

    标签: typescript components aurelia


    【解决方案1】:

    因此,与此同时,我一直在四处打听,并找到了解决方案。见下文。

    组件

    <template>
        <div show.bind="visible" id="sidebar"></div>
    </template>
    
    export class Sidebar {
    
        visible: false;
    
        show = () : void => {
            this.visible = true;
        }
    
        hide = () : void => {
            this.visible = false;
        }
    }
    

    查看

    <template>
        <sidebar sidebar.ref="sidebar" data.bind="data"></sidebar>
        <button click.delegate="show()"></button>
        <button click.delegate="hide()"></button>
    <template>
    
    import {Sidebar} from './sidebar';
    
    export class ViewPage {
    
        sidebar: Sidebar;
    
        show = () : void => {
            this.sidebar.show();
        }
    
        hide = () : void => {
            this.sidebar.hide();
        }
    }
    

    注意sidebar.ref="sidebar"。这将组件和视图绑定在一起。其中第一个sidebar.ref 是组件名称,引号之间的第二个sidebar 是您视图上的属性名称。

    【讨论】:

    • 嗨,Tom,这是使用的正确方法 - 我们在项目中采用的一个不错的替代方法是创建一个服务来管理侧边栏的状态(包括它是否可见或不是)并将其注入到我们希望控制侧边栏的视图中。这还有一个额外的好处是在切换视图时不会丢失侧边栏上下文(假设您的侧边栏是视图的子组件)。
    猜你喜欢
    • 1970-01-01
    • 2022-10-07
    • 2022-09-23
    • 2021-02-04
    • 2021-12-27
    • 2020-03-21
    • 2017-07-22
    • 2019-03-01
    • 2017-12-19
    相关资源
    最近更新 更多