gpt4 book ai didi

javascript - 如何从模块导入的模板文字访问类?

转载 作者:行者123 更新时间:2023-11-29 17:37:43 24 4
gpt4 key购买 nike

导入带有模板文字的模块只能访问全局变量。如何从类中访问变量?

template.js(定位类)

export var literal = {
base: `<h1>${ foo.copy.ternary }</h1>
<div>${ foo.copy.title }</div>
`
}

index.html(在下面的例子中我得到了一个ReferenceError: Can't find variable)

<!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>

模板.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);

关于javascript - 如何从模块导入的模板文字访问类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55232118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com