【问题标题】:EmberJS: passing arguments into componentsEmberJS:将参数传递给组件
【发布时间】:2021-12-23 22:27:03
【问题描述】:

我正在关注关于 Ember.js 的 this 教程,但我正在努力理解一个“简单”的参数传递问题。

我有一个product JSON 对象:

{
  "id": "1",
  "name": "Headphones",
  "colors": [{
    "color": "red",
    "image": "/assets/images/headphones-red.png"
  },
  {
    "color": "black",
    "image": "/assets/images/headphones-black.png"
  }]
},
...
other products with the same structure

并且这个对象被传递给Product 模板中的index.hbs 组件,如下所示:

<Product @product={{product}}/>

Product.hbs 模板中,我有以下内容:

<Product::Image @src={{this.productImage}}/>
<Product::Details 
    @name={{@product.name}}
/>

productImage 是在Product 的组件关联product.js 内部定义的:

import Component from '@glimmer/component';

export default class ProductComponent extends Component {
    productImage = this.args.product.colors[0].image;
}

我的问题是:为什么我必须定义一个特定的组件属性,而不是像使用 name 属性一样?像这样的:

<Product::Image @src={{@product.colors[0].image}}/>

教程不解释,只是说“args代表参数,是传递的属性。这就是我们在JS内部使用传递数据的方式”

谁能启发我?

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    我想没有具体的原因定义一个单独的属性来做到这一点,除非在这种特殊情况下它增加了可读性,即“哦,我们传递产品图像”而不是“我们传递第一个的图像值颜色数组的元素”,但我很确定这是不言而喻的。

    可以按照您的建议执行此操作,但语法略有不同。问题是 hbs 不理解colors[0]。但它会理解colors.[0] 甚至colors.0。可能是这样的

    <Product::Image @src={{@product.colors.[0].image}}/>
    
    or
    
    <Product::Image @src={{@product.colors.0.image}}/>
    
    

    我还玩过twiddle中的一些其他选项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2020-02-06
      • 2018-02-04
      • 1970-01-01
      • 2017-10-24
      • 2018-08-03
      相关资源
      最近更新 更多