【问题标题】:Pass dynamic data attribute to content block in Meteor将动态数据属性传递给 Meteor 中的内容块
【发布时间】:2016-09-15 10:39:44
【问题描述】:

我在 Blaze 中有一个 buttons 的动态模板,看起来像这样(简化):

button.html

<template name="Button">
  <button {{attributes}}>
    <span class="button__text">{{> UI.contentBlock}}</span>
  </button>
</template>

button.js

import {Template} from 'meteor/templating';
import cx from 'classnames';

import './button.html';

Template.Button.helpers({
  attributes() {
    const instance = Template.instance();
    let {data} = instance;

    return {
      disabled: data.disabled,
      'class': cx('button', data.class)
    };
  }
});

尝试设置动态数据属性:

{{#Button class="js-add-contact" data-phase-index={{index}}}}Add Contact{{/Button}}

data-phase-index 中插入index(假设它只是一个简单的动态字符串)会引发错误:内容块不期望{{。我不确定将动态数据放入模板的另一种方法。还有一个问题是让attributes() 助手中的Button 识别data- 属性。谁能解决这个问题?

【问题讨论】:

  • 你能不能把index 的值放到一个helper 中并在attr data-phase-index=getIndex 中引用它?这在Template.dynamics 对我有用。
  • @CodeMonkey 感谢您的输入,index 实际上是一个帮手,我只是犯了一个愚蠢的错误!

标签: meteor meteor-blaze


【解决方案1】:

data-phase-index=index 应该可以工作。

由于您已经在 Button 模板调用的双花括号内,Meteor 知道它将获得解释值。例如,请注意您必须在 class="js-add-contact" 中的字符串周围使用引号。

像往常一样,Meteor 会尝试从帮助程序或数据上下文中解释 index

【讨论】:

  • 不敢相信这么简单!绝对解决了抛出的错误。但是,我的问题的第二部分仍然困扰着我 - 当尝试访问数据属性时,即使使用您的方法,它们也会返回 undefined。如果我在单击按钮时 console.log event.target.dataset,它会打印 DOMStringMap {}
  • 啊,没关系,这是button__text 抛出的事件,它没有任何属性。感谢您的帮助!
  • yw :-) 感谢您的反馈。很高兴您解决了问题的第二部分。
猜你喜欢
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多