javascriptalpine.js

How to dynamically update nested data with dependency on parent?


I have nested alpine.js x-data tags, where the nested tag depends on the parent, like the following:

<div x-data="{foo: 1234}">
  <input x-model="foo" type="number">
  <div x-text="`foo = ${foo}`"></div>
  <div x-data="{bar: [foo*1, foo*2, foo*3]}">
    <template x-for="point in bar">
      <div x-text="point"></div>
    </template>
  </div>
</div>

At the moment, it starts okay, with the output showing:

foo = 1234
1234
2468
3702

However, upon changing the input, the bar values do not update:

foo = 1235
1234
2468
3702

Is it possible to have the nested x-data bar value update dynamically when foo is changed in the parent?

Here is a working example: https://codepen.io/manticorp/pen/RNPBrPK


Solution

  • You’re seeing this issue because Alpine’s x-data initializes once and doesn’t track changes from the parent scope.

    You can define bar as the a computed getter in the parent x-data.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.14.9/cdn.js"></script>
    
    <div x-data="{
        foo: 1234,
        get bar() {
            return [this.foo * 1, this.foo * 2, this.foo * 3];
        }
    }">
      <input x-model="foo" type="number">
      <div x-text="`foo = ${foo}`"></div>
      <template x-for="point in bar">
        <div x-text="point"></div>
      </template>
    </div>