问题描述
我正在研究构建香草网络组件。我以前使用过Polymer,你可以将模板,样式和JavaScript放在一个文件中。如果可能的话,我希望用'vanilla'网页组件实现这一目标,但无法解决问题。我从获取了代码并将其添加到文件中我使用如下:
I am looking into structuring vanilla web-components. I have previously used Polymer and like the fact that you can have the template, styles and JavaScript in one file for your component. I want to achieve this with 'vanilla' web components if possible but can't work out how. I've taken the code from here and added it to a file which I am using as follows:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Component test</title>
<link rel="import" href="x-foo-from-template.html">
</head>
<body>
<x-foo-from-template></x-foo-from-template>
</body>
</html>
这是失败的,因为当我们尝试选择模板时它不存在,因为此时模板是不在DOM中(对吧?)。
This fails because when we try to select the template it does not exist because at that point the template is not in the DOM (right?).
有没有办法实现这个目标?我个人更喜欢这种方法在JavaScript中使用 document.createElement
创建HTML。
Is there any way to achieve this? I personally prefer this approach to creating the HTML in the JavaScript using document.createElement
.
推荐答案
从导入的文档中获取模板有两种主要方法:
There are 2 main methods to get the template from the imported document:
1。来自< link>
元素的 import
属性
1. From the the import
property of the <link>
element
< link rel = import>
元素拥有包含导入文档的属性。
您可以执行 querySelector
调用来获取< template>
:
The <link rel=import>
elements own an import
property that contains the imported document.You can perform a querySelector
call on it to fetch the <template>
:
var doc = document.querySelector( 'link[href$="x-foo-from-template.html"]').import
var template = doc.querySelector( 'template' )
然后在自定义中导入模板元素(或在其Shadow DOM中)使用 importNode()
或 cloneNode()
。
Then import the template in the custom element (or in its Shadow DOM) using either importNode()
or cloneNode()
.
2。形成 currentScript的
ownerDocument
属性
解析脚本时,全局值引用正在解析的脚本,因此它的属性 ownerDocument
是对拥有该脚本的文档的引用。您可以对其执行 querySelector
调用:
When a script is parsed, the global value document.currentScript
references the script being parsed, and therefore its propery ownerDocument
is a reference to the document that owns the script. You can perform a querySelector
call on it:
var template = document.currentScript.ownerDocument.querySelector( 'template' )
注意: currentScript
值设置为暂时,因此在后续调用中不再有效,例如 connectedCallback()
或 attachedCallback()
,因此您必须在解析时将其记忆在持久变量中,以便在以后需要时重复使用。
Note: the currentScript
value is set temporarily, so it won't work any more in subsequent calls, like connectedCallback()
or attachedCallback()
, so you'll have to memorize it in a persistent variable at parse time, to reuse it later when needed.
这篇关于香草网状组件结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!