2016-07-06 65 views
3

自定義元素允許您在使用自定義標記時通過<content></content>選擇器訪問自定義標記的內部html,以及將內容拉入該視圖的某些規範。在類中訪問內容選擇器的自定義元素

我希望能夠訪問我的班級中的這些數據,而不包裝標籤。

我嘗試了以下內容:<content ref="content"></content>this.content引用它繼databinding ref attribute戰略羅布艾森伯格看好,但在元素生命週期的每個階段console.log(this.content)產量undefined

我想到的解決方法是將<content>標記放置在另一個元素中,使用jquery將其拖出文本並緩存,然後通過ref屬性移除該元素,但這看起來不雅觀。

如何在與自定義元素關聯的es6類中訪問這些數據?

示例方案:

一些-view.html

<template> 
    <customelement>Hello World</customelement> 
<template> 

customelement.html

<template> 
    Something, but not a content tag 
</template> 

customelement.js

export class CustomElement { 
    get foobar() { 
     //Somehow ascertain "Hello World" without displaying it in customelement 
    } 
} 

在此示例中,可以假定自定義元素是全局包含的。

+1

'@ processContent'裝飾器能爲你工作嗎? http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/cheat-sheet/9 不確定我是否完全瞭解您的方案 - 請考慮添加一個示例,顯示您的自定義元素的預期用法。 –

+0

@JeremyDanyow看着文檔,我不知道如何繼續以及過程函數如何給出這些參數。我已經用一個最小的例子更新了我的問題,希望這可以清除它 – David

回答

4

我們不再使用content元素。至於RC,我們使用slot元素。也就是說,slot元素不支持ref綁定,因爲slot元素有點「消失」並被替換爲正在投影的內容。這是因爲在Shadow DOM規範中,slot實際上不是元素,它們是「處理指令」。

+0

好吧,沒問題。如何在不使用內容標籤或插槽的情況下訪問數據?我寧願在不修改輸出的DOM的情況下抓取內容。 – David

3

下面是一個示例,顯示您可以在各種組件生命週期階段的內容中訪問哪些內容。

https://gist.run?id=e372bdb91990d08ad49cdf39753cc622 **

app.html

<template> 
    <require from="./my-element"></require> 

    <my-element> 
    <div repeat.for="i of 5">${i}</div> 
    </my-element> 
</template> 

我-element.html

<template> 
    Hello! 
    <slot></slot> 
</template> 

我-element.js

import {inject, processContent, noView} from 'aurelia-framework'; 

@inject(Element) 
export class MyElement { 
    constructor(element) { 
    this.element = element; 
    alert('constructed:\n\n' + this.element.innerHTML); 
    } 

    created() { 
    alert('created:\n\n' + this.element.innerHTML); 
    } 

    bind() { 
    alert('bind:\n\n' + this.element.innerHTML); 
    } 

    attached() { 
    alert('attached:\n\n' + this.element.innerHTML); 
    } 
} 
+0

我測試過,並且意識到我需要添加一點澄清 - 自定義元素仍然應該正常處理和渲染,我只需要提取內容 - 就像您在這裏所做的那樣 - 並按照原樣繼續。 – David

+0

已更新的答案。 –

+0

所以,我認爲重複div是複雜的事情。看看這個要點:https://gist.run/?id = 6b24e48255af21f8e93dd7ae12e65162 - 我想在沒有''的情況下提取「無論」 – David