【问题标题】:How to properly load different set of CSS file in different route in Vuejs project如何在 Vuejs 项目的不同路径中正确加载不同的 CSS 文件集
【发布时间】:2021-01-11 10:11:16
【问题描述】:

我目前正在构建一个 vuejs + laravel 项目,它的管理/用户面板和登录页面的布局会有很大不同,所以我需要为不同的路线加载不同的 CSS 文件。

目前我正在使用 vanilla js 来确定是否要在不同的路径中加载哪个 CSS 文件,我想知道是否有任何适当的方法或适当的方法来做到这一点?

这是我目前的方法: 在每条路由中都会有一个需要加载的 CSS 文件数组,如果 CSS 文件已经加载,脚本将忽略,如果没有,将附加 <link> 以加载 CSS,如果不再需要 CSS 文件,它将被禁用,如果 CSS 文件已经包含但被禁用,它将被重新启用。

router.beforeEach((to, from, next) => {

  // load styles
  if (to.meta.styles) {
    to.meta.styles.forEach((item, i) => {
      let element = document.querySelector(`[rel="stylesheet"][href="${item}"][class="appStyles"]`);

      if (!element) {
        var link = document.createElement( "link" );
        link.href = item;
        link.type = "text/css";
        link.rel = "stylesheet";
        link.setAttribute("class", "appStyles");
        document.getElementsByTagName( "head" )[0].appendChild( link );
      }
    });
  }

  // disable styles
  let existingStyleSheet = document.querySelectorAll(`[rel="stylesheet"][class="appStyles"]`);
  if (existingStyleSheet) {
    // console.log(to.meta.styles);
    existingStyleSheet.forEach((item, i) => {
      if (to.meta.styles) {
        let needed = 0;
        to.meta.styles.forEach((stylesheet, i) => {
          if (item.href == stylesheet) {
            needed += 1;
          }
        });

        // console.log(needed);

        item.disabled = false
        if (needed == 0) {
          item.disabled = true
          item.parentNode.removeChild(item)
        }
      }
    });
  }

...

【问题讨论】:

    标签: javascript css laravel vue.js layout


    【解决方案1】:

    另一种方法是以正常方式(在标题标签内)加载单个 css 文件,并根据布局/页面将特定类传递给 body 标签。希望你明白了.. 确实会有一些不需要的样式,但这会降低复杂性并简化代码维护。这是一个例子:

     $h2-orange: #f60;
     $h2-green: #0f0;
    
     /*common styles - maintains consistancy */
     .h2 {
        font-size: 40px;
        letter-spacing: 1.5px;
        
     }
    
     /* Theme 1 specifics */
     .orange-theme {
         .h2 {
             color: $h2-blue;
          }
          /* other specific styles for Theme 1 */
     }
    
     /* Theme 2 specifics */
     .green-theme {
         .h2 {
             color: $h2-green;
          }
          /* other specific styles for Theme 2 */
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 2019-01-30
      • 2022-08-02
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多