Skip to content

Getter in child component resolves this to parent scope instead of its own component #4814

@serhumanos

Description

@serhumanos

Alpine.js version

v3.15.2

Browser and operating system

Firefox Linux

Describe the issue you're experiencing

When using a getter inside a nested Alpine component, the this context does not reliably refer to the component where the getter is defined. Instead, it may resolve properties from the parent component scope.

This leads to unexpected behavior where a child component getter returns values from the parent

Code snippets to reproduce the issue

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Alpine.js Getter Scope Issue</title>
  <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
</head>
<body>

<div style="font-family: sans-serif; padding: 20px;">
  
  <!-- Parent Component -->
  <div x-data="parent()" style="border: 1px solid #ccc; padding: 10px;">
    <h3>Parent</h3>
    <div>
      <strong>name:</strong>
      <span x-text="name"></span>
    </div>
    <div>
      <strong>getterName:</strong>
      <span x-text="getterName"></span>
    </div>

    <!-- Child Component -->
    <div x-data="child()" style="margin-top: 15px; border: 1px solid #999; padding: 10px;">
      <h4>Child</h4>
      <div>
        <strong>name:</strong>
        <span x-text="name"></span>
      </div>
      <div>
        <strong>getterName:</strong>
        <span x-text="getterName"></span>
      </div>
    </div>
  </div>

</div>

<script>
function parent() {
  return {
    name: 'Parent Component',

    get getterName() {
      return this.name;
    }
  }
}

function child() {
  return {
    name: 'Child Component',

    get getterName() {
      return this.name;
    }
  }
}
</script>

</body>
</html>

Screenshots/screen recordings

No response

How do you expect it to work?

getterVarHijo should return:
Componente Hijo

Please confirm (incomplete submissions will not be addressed)

  • I have provided easy and step-by-step instructions to reproduce the bug.
  • I have provided code samples as text and NOT images.
  • I understand my bug report will be removed if I haven't met the criteria above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions