引用Aurelia组件的ViewModel内的插槽
假设您有以下组件:引用Aurelia组件的ViewModel内的插槽,aurelia,Aurelia,假设您有以下组件: export class Message { messageTxt: string = ""; attached() { // reference the slot HTMLElement here somehow } } 使用以下模板: <template> <div> <slot name="trigger"> </slot> <di
export class Message {
messageTxt: string = "";
attached() {
// reference the slot HTMLElement here somehow
}
}
使用以下模板:
<template>
<div>
<slot name="trigger">
</slot>
<div>${messageTxt}</div>
</div>
</template>
${messageTxt}
正如代码中的注释所暗示的,我想知道如何访问ViewModel中的
元素。我尝试向它添加ref
属性,但它是未定义的
我还尝试向它添加一个父对象,将ref
放在父对象上,并通过访问父对象的直接子对象来获取插槽HTMLElement
。它奏效了,但我想知道是否有更好的解决办法
为了清楚起见,我需要替换
的元素。如果您知道
中标记的名称,可以使用@child
解析器。例如:
消息的视图模型
import {child} from 'aurelia-framework';
export class Element1 {
@child('p') myP;
attached() {
console.log(this.myP);
}
}
import {children} from 'aurelia-framework';
export class Element1 {
@children('ps') myPs = [];
attached() {
console.log(this.myPs);
}
}
import {inject} from 'aurelia-framework';
@inject(Element)
export class Element1 {
constructor(element) {
this.element = element;
}
attached() {
//iterate over this.element.children;
}
}
消息视图
<template>
<slot></slot>
</template>
<template>
<slot name="1"></slot>
<slot name="2"></slot>
</template>
用法
<element1>
<p>test 1 2 3</p>
</element1>
<element1>
<p>test 1 2 3</p>
<p>test 1 2 3</p>
<p>test 1 2 3</p>
</element1>
<template>
<require from="./element1"></require>
<element1>
<p slot="1">sadfasdf</p>
<p slot="2">asdfsadfasd</p>
</element1>
</template>
消息的视图模型
import {child} from 'aurelia-framework';
export class Element1 {
@child('p') myP;
attached() {
console.log(this.myP);
}
}
import {children} from 'aurelia-framework';
export class Element1 {
@children('ps') myPs = [];
attached() {
console.log(this.myPs);
}
}
import {inject} from 'aurelia-framework';
@inject(Element)
export class Element1 {
constructor(element) {
this.element = element;
}
attached() {
//iterate over this.element.children;
}
}
用法
<element1>
<p>test 1 2 3</p>
</element1>
<element1>
<p>test 1 2 3</p>
<p>test 1 2 3</p>
<p>test 1 2 3</p>
</element1>
<template>
<require from="./element1"></require>
<element1>
<p slot="1">sadfasdf</p>
<p slot="2">asdfsadfasd</p>
</element1>
</template>
sadfasdf
asdfsadfasd