简体   繁体   English

Aurelia - 在插槽内引用自定义元素视图模型

[英]Aurelia - Reference custom element view model inside slot

If I have a custom element like this: 如果我有这样的自定义元素:

export class mycomponent {
    constructor() {
         this.name = 'John Doe';
    }
}

<template>
     My component
     <slot></slot>
</template>

And use this component inside another view (I registered the custom element globally): 并在另一个视图中使用此组件(我在全局注册了自定义元素):

<template>
    <mycomponent>
        Test
        ${name}
    </mycomponent>
</template>

Is it possible to access the view model of mycomponent in this scope? 是否可以在此范围内访问mycomponent的视图模型? Like printing out its property name for example? 比如打印出它的属性name

EDIT So here is my final solution: gist my solution 编辑所以这是我的最终解决方案: 我的解决方案

I put the replaceable part inside my custom element: 我把可替换的部分放在我的自定义元素中:

<template>
  <template replaceable part="content"></template>
</template>

and then processContent attribute on the view model: 然后在视图模型上的processContent属性:

import { processContent } from 'aurelia-framework';

@processContent(replacePart)
export class MyComponent {
  name = "John Doe";
}

function replacePart(compiler, resources, node){
    node.innerHTML = `<template replace-part="content">${node.innerHTML}</template>`;
    return true;
}

Like this it works more like a slot with cleaner syntax: 像这样,它更像是一个语法清晰的插槽:

<h4>Component 1</h4>
<my-component>
    <div>One name</div>
    <strong>${name}</strong>
</my-component>

As far as I know, it cannot be achieved using slots. 据我所知,使用插槽无法实现。

However, Aurelia has a feature called replaceable parts : [Blog post] . 但是,Aurelia有一个名为replaceable parts的功能: [博客文章] This might be a better fit for your requirements. 这可能更适合您的要求。

Demo: https://gist.run/?id=dcffe2afcb1eee1777e9b0d9f7366d28 演示: https//gist.run/?id = dcc2afcb1eee1777e9b0d9f7366d28

Edit: HUB docs: [Cheat Sheet / Template Parts] 编辑: HUB文档: [备忘单/模板部件]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM