【问题标题】:How to use typescript object to render a partial view如何使用 typescript 对象呈现局部视图
【发布时间】:2019-11-11 18:37:18
【问题描述】:

到目前为止,我正在使用枚举呈现按钮,然后根据类型我有不同的 HTML。就这样,

export interface control {
  type: controlType;
}

export enum controlType {
  button, 
  switch,
  select
}

那我可以这样称呼,

<!--- ko: if: $data.type === 0 -->
  PUT CODE HERE
<!-- /ko -->

我试图通过使用一个对象来帮助优化,然后在不同的文件中呈现代码视图。我不能让它工作,任何帮助将不胜感激。目前为止,

export interface control {
  type: {
    button: 'folder/button.html',
    switch: 'folder/switch.html',
    select: 'folder/select.html'
  }
}

然后我想我可以使用类似的东西

<!-- ko compose: { view: $data.type } --> <!-- /ko -->

这不起作用,我被卡住了。

【问题讨论】:

    标签: javascript typescript knockout.js


    【解决方案1】:

    interface 仅用于在构建时检查您的类型。由于您的type 对象是在接口内定义的,因此button: 'folder/button.html', 和其他对象在运行时不存在除非您在接口中为$data.type 分配与type 完全相同的对象。

    相反,您可以将controlType 定义为字符串enum

    export enum controlType {
      button = 'folder/button.html', 
      switch = 'folder/switch.html',
      select = 'folder/select.html'
    }
    
    export interface control {
      type: controlType;
    }
    

    现在,您可以创建control 类型的对象,例如:

    const $data: control = {
      type: controlType.button
    }
    

    这会强制 $data.type 只有 3 个可能的值,并允许您像这样使用它:

    <!-- ko compose: { view: $data.type } --> <!-- /ko -->
    

    【讨论】:

      猜你喜欢
      • 2014-08-18
      • 1970-01-01
      • 2020-08-31
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2021-11-19
      • 2012-06-30
      相关资源
      最近更新 更多