内含模板文字的导入模块只能访问全局变量。如何从一个类访问变量?
template.js(定位类)
export var literal = {
base: `<h1>${ foo.copy.ternary }</h1>
<div>${ foo.copy.title }</div>
`
}
index.html(在下面的示例中,我得到一个ReferenceError:找不到变量)
<!DOCTYPE html>
<html>
<body>
<div id=host></div>
</body>
<script type="text/javascript">
class Foo {
constructor() {
this.copy = {
title: 'Discovering Template Literals',
subtitle: 'Effortless client-side rendering awaits.',
body: 'You will never want to go back to normal strings again.',
ternary: 'Ternary Condition'
};
};
};
</script>
<script type="module">
let foo = new Foo();
import * as templates from './templates.js'
document.getElementById( "host" ).innerHTML = templates.literal.base;
</script>
</html>
template.js
export var literal = {
base: `<h1>${ copy.ternary }</h1>
<div>${ copy.title }</div>
`
}
index.html(使用全局变量)
<!DOCTYPE html>
<html>
<body>
<div id=host></div>
</body>
<script type="text/javascript">
var copy = {
title: 'Discovering Template Literals',
subtitle: 'Effortless client-side rendering awaits.',
body: 'You will never want to go back to normal strings again.',
ternary: 'Ternary Condition'
};
</script>
<script type="module">
import * as templates from './templates.js'
document.getElementById( "host" ).innerHTML = templates.literal.base;
</script>
</html>
您的
export var literal = {
base: `<h1>${ foo.copy.ternary }</h1>
<div>${ foo.copy.title }</div>
`
}
会将评估的结果foo.copy.ternary
等插入分配给该base
属性的构造字符串中。但是foo
不在模块范围内,因此在模块运行时将引发错误。
而不是出口的模板文字(这将是不同于导出静态字符串,错误除外),导出功能,这需要foo
作为一个参数,评估模板文字的功能,并返回构建字符串:
export var literal = {
base(foo) {
return `<h1>${ foo.copy.ternary }</h1>
<div>${ foo.copy.title }</div>
`;
}
}
然后调用:
document.getElementById( "host" ).innerHTML = templates.literal.base(foo);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句