How to import internal css conditionally with javascript vuejs?

Issue

Currently, I have to import css file conditionally depend on which kind of browser users are using. To not making css file global, I have the following code:

  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
        }
      },

It does not work because it’s internal css.

I can not import in style tag because there are some link to other images in my css. Importing in style will lead to relative modules were not found

How should I do with without uploading css file to somewhere?

Edit: This question is theoretically the same as what I just did (without jQuery)

Solution

Vuejs compiles in a different way, so import or adding internal css file to head does not work. Simply use require:

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

Answered By – Hùng Nguyễn

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.