vimeshjs / vimesh-ui

Vimesh UI is an ultra lightweight library to build UI components for Alpine.js
MIT License
125 stars 5 forks source link

Using x-model in components #6

Closed flappix closed 12 months ago

flappix commented 12 months ago

Hi, is it possible to use x-model in a component and reflecting the changes outside of the component?

I have a component like this

<template x-component="custom-input">
    <label>
        <span x-html="$prop('label')"></span>
        <input type="text" x-model="model" />
    </label>
</template>

And want to use it in my main html file like

<body x-data="{foo: 'init value'}">
    <vui-custom-input label="label" x-data="{model: foo}"></vui-custom-input>
    <span x-html="foo"></span>
</body>

Issue: The variable foo is not updating when the value inside the component is changed.

https://jsfiddle.net/shtfrjy1/

flappix commented 12 months ago

I came up with this hacky solution but isn't there a cleaner way?

component

<template x-component="custom-input">
    <label>
        <span x-html="$prop('label')"></span>
        <input type="text" x-on:keydown="change ($event.target.value)" />

    </label>
</template>

main html

<body x-data="{foo: 'init value'}">     
    <vui-custom-input label="label" x-data="{change: function(x) {foo=x;} }"></vui-custom-input>
    <span x-html="foo"></span>
</body>

https://jsfiddle.net/shtfrjy1/1

xinjie-zhang commented 12 months ago

Actually, you could use x-modelable (https://alpinejs.dev/directives/modelable)

A good example is vimesh headless combobox :

https://github.com/vimeshjs/vimesh-headless/blob/master/components/combobox.html

flappix commented 12 months ago

Hi thanks a lot for your fast answer. Works great. I updated the fiddle for future reference: https://jsfiddle.net/78det4qx/

Great framework, really love it.