【问题标题】:Select2 is not willing to work with Laravel 9 and Vite? Am I missing something?Select2 不愿意与 Laravel 9 和 Vite 一起工作?我错过了什么吗?
【发布时间】:2022-12-15 09:32:49
【问题描述】:

我刚刚重新安装了一个 Laravel 9 应用程序,使用 npm 添加了 select2 和 jquery,将我需要传递给 vite.config.js 和 app.js 的内容传递给了 vite.config.js 和 app.js,jquery 在加载 select2 之前加载了,但 select2 仍然抛出

Uncaught ReferenceError: jQuery is not defined
    at select2.min.js:2:241
    at select2.min.js:2:249

我什至制作了一个 div#test 并使用 jquery 在加载窗口时将“ok”放入其中,它变为“ok”,但是为什么 select2 会抱怨?

包.json


    "dependencies": {
        "jquery": "^3.6.1",
        "select2": "^4.1.0-rc.0"
    }

vite.config.json文件

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

应用程序.js

import "./bootstrap";
import $ from "jquery";
window.$ = $;
// import { Select2 } from "select2"; // does nothing when uncommented
import 'select2'; // does nothing

$("#test").html("ok");

$(document).on("load",function() { // does nothing
    $(".js-example-basic-single").select2();
});

索引.blade.php

just partial paste
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>

<body>

    <div id="test"></div> <--- this will have "ok" in it since jquery is loaded

    <select class="js-example-basic-single"> <--- this displays as a regular select instead of select2
        <option value="x">asd</option>
        <option value="x">asd</option>
        <option value="x">asd</option>
        <option value="x">asd</option>
    </select>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js" defer></script> <------ if I have this "jquery is not defined" will be thrown
partial paste end

如果我从最后删除 CDN 脚本,它不会再抛出错误,但仍然无法正常工作。此外,CDN 仅在我测试它是否有效时使用,无论如何我都会在本地需要它......

我确实尽了我所能,我已经为此苦苦挣扎了 4 天,但无法弄清楚这有什么问题。

【问题讨论】:

  • 在您的 app.js 中,尝试在 import 'select2'; 下面添加 select2($);
  • Laravel 与 vue.js 开箱即用。您为什么要特意创建一个新项目并改用遗留的 jQuery?除非你有一个必须使用 jQuery 的真实用例,否则我会卸载它并使用建议的 Laravel 前端
  • 我得到的任务包括它作为“必须”,所以我必须在项目中使用它,遗憾的是。我知道 Vue 顺便说一句,期待尝试一下!
  • 我有同样的问题。我通过将其添加到 bootstrap.js 使其部分工作:import select2 from 'select2'; select2(); $('.select2').select2(); 现在唯一的问题是 select2 的 css 不起作用。

标签: jquery laravel jquery-select2 laravel-9


【解决方案1】:

使用npm install select2 --save-dev 安装 Select2 后,您需要将这两行添加到 bootstrap.js,在 jQuery 导入行之后:

import select2 from 'select2';
select2();

还将 Select2 CSS 添加到 app.scss:

@import "/node_modules/select2/dist/css/select2.css";

在您的 JavaScript 中,您可以像以前一样使用它:

$(".js-example-basic-single").select2();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-30
    • 2021-08-05
    • 2021-11-28
    • 2020-09-14
    • 1970-01-01
    • 2022-01-13
    • 2020-09-21
    • 2011-10-22
    相关资源
    最近更新 更多