1

We are working with Vue and the client has asked us for a button that allows him to choose the theme that he prefers.

The point is, I need to dynamically load the css file that corresponds to each theme.

I have tried this: How to load css file dynamically but I haven't made it work.

My code:

Account.vue:

multiselect(
           v-model="theme",
           :placeholder="$t('Select')",
           label="name",
           track-by="code",
           :showLabels="false"
           :options="themes",
           :multiple="false",
           :taggable="false",
           :selectLabel="$t('SelectLabel')",
    .columns
      .column.has-text-centered
         button.button(@click='sendData, appendFile', :disabled="!language || !rol || !theme") {{ $t('Save') }}

JS:

data() {
    return {
      theme: null,
      themes: [
        { name: 'Default', code: 'def' },
        { name: 'Montich', code: 'mont' },
      ],
    };
  },

methods: {
    sendData() {
       this.$store.dispatch('THEME_SELECT', this.theme.code).then(() => {
      });
    appendFile() {
      const file = document.createElement('link');
      file.rel = 'stylesheet';
      file.href = 'assets/css/montich.css';
      file.head.appendChild(file);
    },
  },

Now some prints: ...Files ...Network and view Thanks in advance!

11
  • Why not change the class of the button when the state theme changes? For example, you can switch the class between button--default and button--montich . You don't need to load css files dynamically. That's not a good way to create components. Commented Jun 7, 2020 at 4:57
  • Hi @ThetAung Well, I thought the same and that is what I proposed to my leader (I am a trainee and my first working week as a web dev has just finished), and he told me that since there are many clients who will have different themes, it would be less than optimal load all styles on a single css sheet. So he asked that each theme be loaded on a different style sheet ... Commented Jun 7, 2020 at 5:00
  • You should tell him that when the user tries to change to a different theme requesting another css file from server (which you're trying to do) is not a good practice. It's be much slower than adding a few line of css code for each theme even if there's 100 of them. Any library that creates components never do that. Commented Jun 7, 2020 at 5:05
  • You might be interested in this codyhouse.co/blog/post/dark-light-switch-css-javascript Commented Jun 7, 2020 at 5:12
  • Thank you @ThetAung! I'll keep your advice in mind and i'll talk to my leader about your proposal. Of course im going to check your link right now. Appreciate it! Commented Jun 7, 2020 at 5:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.