【问题标题】:How to import internal css with javascript vuejs?如何使用 javascript vuejs 导入内部 css?
【发布时间】:2020-04-10 17:18:33
【问题描述】:

目前,我必须有条件地导入 css 文件,这取决于用户使用哪种浏览器。为了不使 css 文件全局化,我有以下代码:

  created() {
      this.checkIsMobile()
  },
  methods: {
      checkIsMobile(){
        var isMobile = new MobileDetect(window.navigator.userAgent);
        if (isMobile.mobile()){
          $('head').append('<link rel="stylesheet" type="text/css" href="@/assets/css/main-pc.css">');
        }else {
          $('head').append('<link rel="stylesheet" type="text/css" href="@/assets/css/main-m.css">'); //must be load external css
        }
      },

它不起作用,因为它是内部 css。

我无法导入样式标签,因为我的 css 中有一些指向其他图像的链接。导入风格会导致relative modules were not found

如果不将css文件上传到某个地方,我该怎么办?

编辑:This question 理论上和我刚刚做的一样(没有 jQuery)

【问题讨论】:

  • 为什么你的 VueJS 应用中有 jQuery?对于您的 VueJS 应用程序,您使用的是 webpack 之类的打包工具吗?如果你是,这可能会有所帮助:stackoverflow.com/a/52769714/395910
  • 为什么不只是静态地包含一个 CSS 文件并使用媒体查询来覆盖较小的屏幕尺寸的不同规则?
  • 这能回答你的问题吗? How to load css file dynamically

标签: javascript css vue.js


【解决方案1】:

Vuejs 以不同的方式编译,因此导入或添加内部 css 文件到 head 不起作用。只需使用require:

    if (isMobile.mobile()){
      require('@/assets/css/mobile.css');
    }else {
      require('@/assets/css/pc.css');
    }

【讨论】:

    【解决方案2】:

    你可以试试下面的方法吗?

    <style scoped>
    @import './../file.css';
    </style>
    

    来源网址:https://forum.vuejs.org/t/how-to-import-css-files-into-single-file-component/41337

    【讨论】:

    • 我不能在条件下使用它
    【解决方案3】:

    你不应该使用 JQuery。它速度慢、体积大,而且你使用 jquery 可以在 Vue 中做的所有事情。

    其次,你不应该在 JS 中检测屏幕大小,而是在 CSS 中。

    https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

    【讨论】:

    • 我使用这个库github.com/hgoebl/mobile-detect.js 来检测屏幕尺寸,看起来很可靠。使用 CSS 检测移动设备可能是答案,但它破坏了我的工作流程
    猜你喜欢
    • 1970-01-01
    • 2017-12-12
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多