You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vue时如何在Blade文件中引入第三方组件?遇404错误求助

解决Laravel Blade中无法引入vue3-select2-component的问题

问题原因

浏览器无法直接访问项目根目录下的node_modules文件夹——Web服务器的根目录是Laravel的public目录,请求/node_modules/...会去public下查找,自然返回404。

解决方案

方法一:用Laravel打包工具处理(推荐,适合生产环境)

如果你的Laravel版本是9+,默认用Vite;更早版本用Mix,步骤如下:

  1. 在项目的入口JS文件(如resources/js/app.js)中导入并注册组件:
import { createApp } from 'vue';
import Select2 from 'vue3-select2-component';

const app = createApp({});
// 全局注册组件,也可以在单个组件内局部注册
app.component('Select2', Select2);
app.mount('#app');
  1. 执行打包命令:
    • Vite:运行 npm run dev(开发环境)或 npm run build(生产环境)
    • Mix:运行 npm run dev(开发环境)或 npm run production(生产环境)
  2. 在Blade文件中引入打包后的资源,替换原有的CDN和模块脚本:
    • Vite项目:添加 @vite('resources/js/app.js')
    • Mix项目:添加 <script src="{{ mix('js/app.js') }}"></script>

方法二:手动复制组件文件到public目录

  1. 找到myproject/node_modules/vue3-select2-component/dist/vue3-select2-component.umd.min.js,复制到public/js/目录下
  2. 在Blade中引用该文件并注册组件:
@push('js')
    <script src="https://unpkg.com/vue@3"></script>
    <script src="{{ asset('js/vue3-select2-component.umd.min.js') }}"></script>
    <script>
        const app = Vue.createApp({});
        // UMD包暴露的全局组件名是Vue3Select2Component
        app.component('Select2', Vue3Select2Component);
        app.mount('#app');
    </script>
@endpush

方法三:直接使用CDN引入组件

跳过本地npm安装,直接用CDN链接引入:

@push('js')
    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/vue3-select2-component"></script>
    <script>
        const app = Vue.createApp({});
        app.component('Select2', Vue3Select2Component);
        app.mount('#app');
    </script>
@endpush

内容的提问来源于stack exchange,提问作者vbnewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:02:21