如何在 Astro JS 中将变量从 frontmatter 传递到脚本?

Ale*_*sky 1 javascript astro

如何在 Astro js 中将变量从 frontmatter 传递到脚本。像这样:

---
const title = "this is title"
---

some content


<script>

const metatile = title

<script>
Run Code Online (Sandbox Code Playgroud)

The*_*ord 13

您可以使用该define:vars指令将值传递给客户端。

---
const title = "this is title"
---

<script define:vars={{title}}>
  alert(title);
<script>
Run Code Online (Sandbox Code Playgroud)

上述方法将禁用任何 Vite 捆绑。如果您需要由 Vite 分析和捆绑脚本(如果它使用 TypeScript 或导入),您可以使用第二种方法将值设置为data-*属性,然后在客户端上读取它。

---
const message = "Hello world";
---

<!-- Store the message prop as a data attribute. -->
<astro-greet data-message={message}>
  <button>Say message</button>
</astro-greet>

<script>
  class AstroGreet extends HTMLElement {
    constructor() {
      super();

      // Read the message from the data attribute.
      const message = this.dataset.message;

      const button = this.querySelector('button');
      button.addEventListener('click', () => {
        alert(message);
      });
    }
  }

  customElements.define('astro-greet', AstroGreet);
</script>
Run Code Online (Sandbox Code Playgroud)