首页 > 解决方案 > Vue - 我如何在组件中加载 CSS 和 JS 文件?

问题描述

我对 Vue 很陌生,我创建了一个要加载的导航栏组件。

这是我的代码:

组件.vue

<template>
    <html>
        <head>
        ...
        <link href="https://fonts.googleapis.com/css?family=Gudea:400,700" rel="stylesheet">
        <link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link href="assets/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet">

        <!-- Theme Styles -->
        <link href="assets/css/flatifytheme.min.css" rel="stylesheet">
        <link href="assets/css/custom.css" rel="stylesheet">
        ...
        </head>
        <body>
         ...
        
         <script src="assets/plugins/jquery/jquery-3.1.0.min.js"></script>
         <script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
         <script src="assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js"></script>
         <script src="assets/plugins/waves/waves.min.js"></script>
         <script src="assets/plugins/uniform/js/jquery.uniform.standalone.js"></script>
         <script src="assets/plugins/switchery/switchery.min.js"></script>
         <script src="assets/plugins/pace/pace.min.js"></script>
         <script src="assets/js/flatifytheme.min.js"></script>

        </body>
    </html>
</template>

assets目录与组件位于同一文件夹中。

现在的问题是我有很多<link href=''>标签<scripts>来加载我用于导航栏的主题的 js 和 css 文件,我不知道将它们放在组件中的哪个位置,所以我不断收到以下错误:

This relative module was not found:
* ./components/testComponent in ./src/main.js, ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=script&lang=js&

这个错误是什么意思?我该如何解决?

标签: javascriptvue.js

解决方案


有两种方法可以做到这一点:

  1. 这些都是您项目中的全局文件
    • 直接在 index.html 中加载远程文件(谷歌字体任何 http 文件)
    • main.js通过您的或中的捆绑程序加载项目文件App.vue
    • 等等import '@/assets/plugins/bootstrap/css/bootstrap.min.css'……
  2. 或者,这些是需要在特定组件中加载的本地文件
    • 使用 vue-meta 插件加载远程文件(谷歌字体或任何 http 文件),该插件可帮助您在head标签https://vue-meta.nuxtjs.org/api中即时创建链接、脚本和其他 HTML 标签/#关联
    • import '@/path/to/js/file'使用JS 文件或 CSS加载项目文件:
<style>
@import '@/path/to/js/file';
</style>

推荐阅读