Riccardo LV
Riccardo LV

Reputation: 192

Alpine JS - Extracting Component Logic issue

I'm struggling with a ToDo app I'm coding from scratch (in order to learn Alpine).

If I write this it works:

<div x-data="{myArray:[], newTask: ''}">
    New task: 
    <input type="text" x-model="newTask" @keyup.enter="myArray.push(newTask); newTask = '';">

But it doesn't work if I try to extract @keyup.enter function this way:

<div x-data="{myArray:[], newTask: '', add_newTask() {myArray.push(newTask); newTask = '';}}">
    New task: 
    <input type="text" x-model="newTask" @keyup.enter="add_newTask()">

What am I doing wrong?

Upvotes: 0

Views: 422

Answers (1)

Dauros
Dauros

Reputation: 10502

When you put the add_newTask() method to the x-data directive, you are creating an Alpine.js component (like with Alpine.data()). Inside a component you have to use the this. prefix to access the data of the component for example this.myArray:

<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

<div x-data="{myArray:[], newTask: '', add_newTask() {this.myArray.push(this.newTask); this.newTask = '';}}">
    New task: 
    <input type="text" x-model="newTask" @keyup.enter="add_newTask()">
    
    <div x-show="myArray.length">
      <h2>Tasks</h2>
      <ul>
      <template x-for="task in myArray">
        <li :key="task" x-text="task"></li>
      </template>
      </ul>
    </div>
</div>

Upvotes: 1

Related Questions