Livewire 3和Laravel Breeze 错误:Alpine.js冲突
如果你尝试将Livewire 3与Laravel Breeze入门套件一起使用,你可能会注意到你的组件没有反应,Livewire的一些功能就是不起作用。原因可能是Alpine.js,它被加载了两次。
在浏览器控制台中,您可能看到以下错误:
或任何其他类似错误:
Uncaught TypeError: window.Alpine.cloneNode is not a function
Uncaught (in promise) TypeError: Alpine.navigate is not a function
Uncaught (in promise) TypeError: l is not a function
Uncaught TypeError: Alpine.store is not a function
此错误是由Livewire和Breeze冲突引起的:
Laravel Breeze在resources/js/app.js文件中默认启用Alpine.js
Livewire v3还内置了Alpine并已预先配置
但别担心。您可以通过几个简单的步骤来修复它:
解决方案
步骤1:打开resources/js/app.js
步骤2:删除以下3行:
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
步骤3:运行 npm Run build
以再次构建资源文件。
步骤4:打开 resources/views/layouts/app.blade.php
第五步:添加 @livewireStyles
和 @livewireScripts
如下:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />
<!-- Scripts -->
@vite(['resources/css/app.css', 'resources/js/app.js'])
@livewireStyles
</head>
<body class="font-sans antialiased">
<div class="min-h-screen bg-gray-100">
@include('layouts.navigation')
<!-- Page Heading -->
@if (isset($header))
<header class="bg-white shadow">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
{{ $header }}
</div>
</header>
@endif
<!-- Page Content -->
<main>
{{ $slot }}
</main>
</div>
@livewireScripts
</body>
</html>
就是这样!您刚刚禁用了Alpine,并允许Livewire内置的Alpine完成其工作。
您现在应该有一个反应式组件,并且控制台上不再有错误。
本作品采用《CC 协议》,转载必须注明作者和本文链接