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

component gets initialized twice, when used in dynamic html #4

Open cwmoss opened 1 year ago

cwmoss commented 1 year ago

i want to use some components in dynamicly loaded markup. unfortunately they will be initialized twice. do you know of a way of avoiding this?

example:

<head>
    <script src="https://unpkg.com/@vimesh/ui"></script>
    <script src="//unpkg.com/alpinejs" defer></script>
</head>

<body>
    <h1>Test..</h1>
    <div x-data="{html: ''}" x-init="setTimeout(()=>{html='<h2>hello</h2><vui-test></vui-test>'}, 2000)">
        <div x-html="html"></div>
    </div>
      <template x-data x-component="test" x-init="$api && $api.init()">
        <div class="toplist">
            <button x-on:click="console.log('hi from web component')">test</button>
        </div>
        <script>
            return {
                init() {
                    console.log(`init test component`)
                },
            }
        </script>
    </template>
</body>

on codepen

xinjie-zhang commented 1 year ago

This is a known issue because of the x-html internal implementation in alphinejs. Vimesh UI provides an alternative x-shtml, means safe html. For your problem, just replace x-html to x-shtml

xinjie-zhang commented 1 year ago

You could also refer to /examples/spa/app.html , which is a minimal single page application framework with vimesh ui. x-shtml is used to load dynamic pages, with help of x-import:dynamic, these pages will be lazy loaded.

cwmoss commented 1 year ago

this is so cool! it just works! i really missed this x-shtml. i think it belongs on the README :) now i'm able to include alpine driven components in markdown. alpinejs should make this an official components extension. or maybe it's time for a mesh-up: the best of petite-vue & alpine plus tight component support (with the least necessary new syntax/magix).

let's dream:

all the best!