如何在astroJS中使用文档和窗口元素



我想使用窗口或文档返回当前页面的默认路径Astro.site.pathname工作不正常或没有合适的文档。

我的问题是如何在AstroJS中正确使用文档或窗口?

提前感谢!

如果要使用windowdocument之类的东西,则需要在<script is:inline></script>中编写脚本。这样Astro就不会触及你的JS并将其直接包含在HTML中。位于--- ---之间页面顶部的JS将在构建时执行。

您还可以使用const { pathname } = Astro.url从Astro组件访问当前路径名。

脚本标记

文档中提到的<script>标签足以使用文档和窗口,因为它适用于客户端Javascript

https://docs.astro.build/en/guides/client-side-scripts/#using-astro 中的脚本

内联脚本

如果您不需要<script is:inline>,则不建议使用它,因为它旨在避免捆绑您的脚本,而这是很少需要的。如果您使用包含该脚本的组件,例如在10个实例(e,g,10张卡(中,您将使该脚本重复10次,因此会对加载性能产生影响。

https://docs.astro.build/en/guides/client-side-scripts/#script-捆绑

示例

这个例子展示了如何在纯Astro中创建多个客户端计数器,这与纯html类似。注意document.querySelectorAll(".card")document的用法

中的更多详细信息https://docs.astro.build/en/core-concepts/astro-components/

---
//Astro Front matter => Javascript
---
<!-- html -->
<!-- style -->
<!-- script -->
<script>
console.log("int cards")
const cards = document.querySelectorAll(".card")
cards.forEach(card => {
const plus = card.querySelector('button.plus')
const minus = card.querySelector('button.minus')
const value = card.querySelector(".value")
plus.onclick  = ()=>{value.textContent = parseInt(value.textContent) + 1}
minus.onclick = ()=>{value.textContent = parseInt(value.textContent) - 1}
});
</script>

这里有一个完整的回购项目示例链接:

https://github.com/MicroWebStacks/astro-examples#04_client-计数器

这里有一个直接指向StackBlitz项目的链接,指向回购

https://stackblitz.com/github/MicroWebStacks/astro-examples/tree/main/04_client-counters

默认情况下,Astro将处理、优化和捆绑它在页面上看到的任何和标记。您可以使用is:inline指令选择退出此行为。

文档

您可以在.astro组件中使用类似的is:inline指令:

---
// static build only
---
<script is:inline>
console.log(document, window)
</script>

最新更新