如何在组件中呈现动态HTML? [英] How can I render dynamic HTML in component?

查看:103
本文介绍了如何在组件中呈现动态HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Ember车把模板,并且我想通过onclick事件侦听器将其动态呈现到DOM。

I have the following Ember handlebar template and I want to render it to DOM dynamically including with the onclick event listener. How to do it in EmberJS?

hello.js

export default Ember.Component.extend({
    didInsertElement() {
        var message = `
            <p>Hello World!</p>
            <a onclick={{action "handleOpenUrl"}}>Learn More</a>
        `;
        this.set('message', message);
    },

    actions: {
        handleOpenUrl() {
            //open url code
        }
    }
});

hello.hbs

{{{message}}}

DOM中的预期输出

<p>Hello World!</p>
<a>Learn More</a>

当我单击了解更多信息时, handleOpenUrl 应该被称为

And when I click on Learn More, handleOpenUrl should be called

推荐答案

您应该具有以下类似内容:

You should have something more like this:

export default Ember.Component.extend({
   showMessage:false,
   actions: {
        handleOpenUrl() {
            //open url code
        }
    }
});



hello.hbs



hello.hbs

{{#if showMessage}}
   <p>Hello World!</p>
   <a {{action "handleOpenUrl"}}>Learn More</a>
{{/if}}

然后切换 showMessage 隐藏或显示您的HTML。您的动作声明也是错误的(我已经在上面进行了更正),请参见 https:// guides。 emberjs.com/release/templates/actions/

you then toggle showMessage to hide or show your HTML. Your action declaration is also wrong (I've corrected above), see https://guides.emberjs.com/release/templates/actions/

然后在主要途径中消耗该组件:

you then consume the component in your main route:

{{hello showMessage=true}}

如果要呈现不同的HTML,则需要使用 yield

If you want to render different HTML then you'll need to use yield:

{{#if showMessage}}
   {{yield}}
{{/if}}

这将允许您以这种方式使用组件:

this will allow you to consume your component this way:

{{#hello showMessage=true}}
   <p>Hello World!</p>
   <a {{action "handleOpenUrl"}}>Learn More</a>
{{/hello}}

您的操作 现在不存在于组件中。您现在需要将该操作保存在控制器中。 TBH如果您要这样做,我看不出使用组件的意义。只需使用标准的 {{#if}}

Your action now doesn't live in the component. You'll need the action to be in controller now. TBH I don't see the point in using a component if you want to do this. Just use a standard {{#if}}

似乎您只是在尝试重用 onclick 操作。如果是这种情况,请使用 mixin 服务是不成为组件的方法。

It seems that your just trying ot reuse the onclick action. If this is the case then a mixin or a service is the way to go not a component.

这篇关于如何在组件中呈现动态HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆