html 如何重用AlpineJs数据?

7kjnsjlb  于 2022-12-09  发布在  其他
关注(0)|答案(2)|浏览(212)
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>

<div x-data="info">
  <span x-text="data"></span>
</div>

<div x-data="info">
  <span x-text="data"></span>
</div>

<script>
  let info ={
  data: "hello"
}

document.addEventListener("alpine:init", () => {
    info = Alpine.reactive(info)
    Alpine.data("info", () => info);
 });
</script>

以上代码给出以下错误:

如何解决这个问题并重用AlpineJS数据?

hm2xizp9

hm2xizp91#

可以使用Alpine.store访问全局Alpine状态。(https://alpinejs.dev/magics/store

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>

<div x-data>
  <span x-text="$store.info.data"></span>
</div>

<div x-data>
  <span x-text="$store.info.data"></span>
</div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.store('info', {
            data: "Hello 👋🏼"
        })
    })
</script>
ctrmrzij

ctrmrzij2#

它不起作用,因为每个x-data将重新初始化其express,意味着将magics,Alpine.data注入x-data结果。在您的情况下,两个x-data引用同一个对象“info”。此信息将初始化两次,在第二次注入“$nextTick”magic时失败。解决方案将使x-data引用其自己的根对象,为它们的属性分配公共“信息”。下面是一个修改后的版本:

<head>
  <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.js"></script>
</head>

<body>
  <div x-data="first">
    <span x-text="info.data"></span>
  </div>

  <div x-data="second">
    <span x-text="info.data"></span>
  </div>

  <script>
    let first = {}
    let second = {}
    let info = {
      data: "hello"
    }

    document.addEventListener("alpine:init", () => {
      info = Alpine.reactive(info)
      first.info = second.info = info
      setTimeout(() => {
        info.data = "world"
      }, 1000)
    });
  </script>
</body>

相关问题