使用Alpine.js在全新的Laravel 10安装中与Vite存在问题。

huangapple go评论86阅读模式
英文:

Issue Using Alpine.js with Vite in a fresh Laravel 10 installation

问题

I've translated the non-code part of your content:

我一直在尝试首次使用Vite,我更熟悉Laravel Mix。当我在app.js中包含Alpine函数并使用npm run build构建时,这些函数似乎无法从标记中的指令中运行。以下是我的代码:

index.blade.php中:

<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 grid grid-cols-1 md:grid-cols-3 gap-4" x-data="solar">
    <form @submit.prevent="addComponent">
        <div class="mt-4">
            <x-select-input id="component" :items="$products->pluck('name', 'id')"></x-select-input>
        </div>
        <div class="mt-4">
            <x-primary-button>Add Component</x-primary-button>
        </div>
    </form>
</div>

<div>
    <ul class="w-96">
        <template x-for="component in components">
            <li class="w-full border-b-2 border-neutral-100 border-opacity-100 py-4 dark:border-opacity-50" x-text="component.name"></li>
        </template>
    </ul>
</div>

app.js中:

import './bootstrap';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();

document.addEventListener('alpine:init', () => {
    Alpine.data('solar', () => ({
        components: [],
        addComponent(elem) {
            let item = document.getElementById('component');
            this.components.push({
                id: item.value,
                name: item.options[item.selectedIndex].text,
            });
        },
    }));
});

vite.config.js中:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
            ],
            refresh: true,
        }),
    ],
});

如果在视图(index.blade.php)中的<script>标签中包含相同的Alpine.data()函数,它可以完美运行。但是,当它放在app.js中并包含在生成的构建中时,我会收到以下错误消息:

Alpine 表达式错误:addComponent 未定义
表达式:"addComponent"

如何解决这个问题并将我的函数放在 Vite 构建中而不是在视图中?

英文:

I've been attempting to use Vite for the first time, I'm more familiar with Laravel Mix. It appears that when I include alpine functions in app.js and build with npm run build those functions cannot be run from the directives in the markup. Heres my code:

in index.blade.php:

&lt;div
	class=&quot;max-w-7xl mx-auto sm:px-6 lg:px-8 grid grid-cols-1 md:grid-cols-3 gap-4&quot;
	x-data=&quot;solar&quot;
&gt;
	&lt;form @submit.prevent=&quot;addComponent&quot;&gt;
		&lt;div class=&quot;mt-4&quot;&gt;
			&lt;x-select-input id=&quot;component&quot; :items=&quot;$products-&gt;pluck(&#39;name&#39;, &#39;id&#39;)&quot;&gt;&lt;/x-select-input&gt;
		&lt;/div&gt;
		&lt;div class=&quot;mt-4&quot;&gt;
			&lt;x-primary-button&gt;Add Component&lt;/x-primary-button&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;

&lt;div&gt;
	&lt;ul class=&quot;w-96&quot;&gt;
		&lt;template x-for=&quot;component in components&quot;&gt;
			&lt;li
				class=&quot;w-full border-b-2 border-neutral-100 border-opacity-100 py-4 dark:border-opacity-50&quot;
				x-text=&quot;component.name&quot; &gt;
			&lt;/li&gt;
		&lt;/template&gt;
	&lt;/ul&gt;
&lt;/div&gt;

in app.js:

import &#39;./bootstrap&#39;;

import Alpine from &#39;alpinejs&#39;;

window.Alpine = Alpine;

Alpine.start();


document.addEventListener(&#39;alpine:init&#39;, () =&gt; {
    Alpine.data(&#39;solar&#39;, () =&gt; ({

        components: [],

        addComponent(elem) {
            let item = document.getElementById(&#39;component&#39;);
            this.components.push({
                id: item.value,
                name: item.options[item.selectedIndex].text,
            });
        },
    }));
});

And in vite.config.js:

import { defineConfig } from &#39;vite&#39;;
import laravel from &#39;laravel-vite-plugin&#39;;

export default defineConfig({
    plugins: [
        laravel({
            input: [
                &#39;resources/css/app.css&#39;,
                &#39;resources/js/app.js&#39;,
            ],
            refresh: true,
        }),
    ],
});

If include the same Alpine.data() function in a script tag within the view (index.blade.php), it works flawlessly: but when it's placed within app.js and included in the resulting build I get the error:

Alpine Expression Error: addComponent is not defined

Expression: &quot;addComponent&quot;

How can I solve this and put my functions in the Vite build instead of in the view?

答案1

得分: 1

以下是翻译好的内容:

Alpine.js文档所述:

> 如果你将Alpine导入到一个捆绑包中,你必须确保在导入Alpine全局对象时和调用Alpine.start()初始化Alpine之间注册任何扩展代码。

对我来说,这似乎只是一个排序问题(我以前也遇到过相同的问题)。在所有的alpine.js代码之后调用Alpine.start()。你的app.js应该类似于这样:

import Alpine from 'alpinejs';
window.Alpine = Alpine;

Alpine.data('solar', () => ({ ... }));

Alpine.start();

请注意,在使用这样的构建系统时,你不需要'alpine:init'事件监听器。查看文档中的这个部分以获取示例。我建议将所有的alpine.js组件从app.js中提取到单独的文件中,以更好地分离关注点,并当你开始添加更多组件时,防止app.js变得过于臃肿。类似这样:

// app.js
import Alpine from 'alpinejs';
window.Alpine = Alpine;

import component1 from './alpine_components/component1.js';
import component2 from './alpine_components/component2.js';
...

Alpine.data('component1', component1);
Alpine.data('component2', component2);
...

Alpine.start();
// alpine_components/component1.js
export default () => ({
	...
});
英文:

As stated in the alpine.js docs:

> If you imported Alpine into a bundle, you have to make sure you are registering any extension code IN BETWEEN when you import the Alpine global object, and when you initialize Alpine by calling Alpine.start().

To me it looks like this shouldn't be anything but just an ordering issue (I've had the same problem myself before). Call Alpine.start() AFTER all of your alpine.js code. Your app.js should look something like this:

import Alpine from &#39;alpinejs&#39;;
window.Alpine = Alpine;

Alpine.data(&#39;solar&#39;, () =&gt; ({ ... }));

Alpine.start();

Note that you don't need the &#39;alpine:init&#39; event listener when using a build system like this. Have a look at this section in the docs for an example. I'd recommend extracting all of your alpine.js components out of app.js into individual files for better separation of concerns, and of course to prevent your app.js from becoming too bloated when you start adding more components. Something like this:

// app.js
import Alpine from &#39;alpinejs&#39;;
window.Alpine = Alpine;

import component1 from &#39;./alpine_components/component1.js&#39;;
import component2 from &#39;./alpine_components/component2.js&#39;;
...

Alpine.data(&#39;component1&#39;, component1);
Alpine.data(&#39;component2&#39;, component2);
...

Alpine.start();
// alpine_components/component1.js
export default () =&gt; ({
	...
});

huangapple
  • 本文由 发表于 2023年5月14日 20:48:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定