Patrick Quijano
Patrick Quijano

Reputation: 351

How can we pass parameters to Alpine.data in Alpine.js v3?

I am now using the newest version of Alpine which is v3.

Making reusable components needs to be registered using the Alpine.data.

This is the alpinejs.js

import Alpine from 'alpinejs'
import form from './components/form'

window.Alpine = Alpine

Alpine.data('form', form)

Alpine.start()

This is what I have in the components/form.js

export default (config) => {
  return {
    open: false,
    init() {
      console.log(config)
    },
    get isOpen() { return this.open },
    close() { this.open = false },
    open() { this.open = true },
  }
}

This is the html part:

<div x-data="form({test:'test'})"></div>

This is the error I get in the console:

Alpine.js Console Error

Any idea how to pass parameters to Alpine.data?

Upvotes: 3

Views: 6766

Answers (2)

AlexGalax
AlexGalax

Reputation: 310

I stumbled over this question, searching for an answer but figured it out now. Maybe its still usefull to someone...

You have do define the parameter when registering the data component:

document.addEventListener('alpine:init', () => {

    window.Alpine.data('myThing', (param) => MyModule(param));

});

Now you can use it in your module on init...

export default (param) => ({
    init() {
        console.log(param);
    }
});

... when you init the component

<div x-data="deliveryDate({ foo: 'bar' })"></div>

Upvotes: 2

usersina
usersina

Reputation: 1845

This likely happens since you imported your script as a module. Therefore, you need another script that handles initialization of data.

I'm using a vanillajs vite setup and here's a working implementation with alpinejs:

index.html

<head>
    <!-- Notice the type="module" part -->
    <script type="module" src="/main.js" defer></script>

    <script src="/initializer.js"></script>
</head>

<body x-data="greetingState">
  <button @click="changeText">
    <span x-text="message"></span>
  </button>

  <h2 x-text="globalNumber"></h2>
</body>

main.js

import Alpine from 'alpinejs';

window.Alpine = Alpine;
Alpine.start();

// const globalNumber = 10; // Wrong place

initialize.js

document.addEventListener('alpine:init', () => {
  Alpine.data('greetingState', () => ({
    message: "Hello World!",

    changeText() {
      this.message = "Hello AlpineJs!";
    },
  }));
});

const globalNumber = 10; // Correct place

Note that listening to the alpine:init custom event inside of a javascript module will break the app. The same happens if you try to display a variable from a script of type module, in this example globalNumber.

Upvotes: 1

Related Questions