muse-ui动态加载主题色

muse-ui动态加载主题色

Posted by MaxBear 4 years ago

muse-ui动态加载主题色

打开官方的demo

<template>
<mu-tabs :value="theme" @change="changeTheme">
  <mu-tab title="LIGHT (DEFAULT)" value="light"/>
  <mu-tab title="DARK" value="dark"/>
  <mu-tab title="CARBON" value="carbon"/>
  <mu-tab title="TEAL" value="teal"/>
</mu-tabs>
</template>
<script>
import light from '!raw!muse-ui/dist/theme-default.css'
import dark from '!raw!muse-ui/dist/theme-dark.css'
import carbon from '!raw!muse-ui/dist/theme-carbon.css'
import teal from '!raw!muse-ui/dist/theme-teal.css'
export default {
  data () {
    return {
      theme: 'light',
      themes: {
        light,
        dark,
        carbon,
        teal
      }
    }
  },
  methods: {
    changeTheme (theme) {
      this.theme = theme
      const styleEl = this.getThemeStyle()
      styleEl.innerHTML = this.themes[theme] || ''
    },
    getThemeStyle () {
      const themeId = 'muse-theme'
      let styleEl = document.getElementById(themeId)
      if (styleEl) return styleEl
      styleEl = document.createElement('style')
      styleEl.id = themeId
      document.body.appendChild(styleEl)
      return styleEl
    }
  }
}
</script>

完全没有效果

而且还报了4个错误

报错

仔细再看一遍文档有这么一句动态的切换主题,需要依赖 webpack 的 raw-loader 加载器

那我们安装一下raw-loader模块

cnpm install --save-dev raw-loader

然后修改一下import方式

!raw!改成!raw-loader!

import light from '!raw-loader!muse-ui/dist/theme-default.css'
import dark from '!raw-loader!muse-ui/dist/theme-dark.css'
import carbon from '!raw-loader!muse-ui/dist/theme-carbon.css'
import teal from '!raw-loader!muse-ui/dist/theme-teal.css'

然后重新加载一下页面

详细代码如下 Hello.vue

<template>
  <div class="hello">
    <mu-tabs :value="theme" @change="changeTheme">
      <mu-tab title="LIGHT (DEFAULT)" value="light"/>
      <mu-tab title="DARK" value="dark"/>
      <mu-tab title="CARBON" value="carbon"/>
      <mu-tab title="TEAL" value="teal"/>
    </mu-tabs>
  </div>
</template>

<script>
import light from '!raw-loader!muse-ui/dist/theme-default.css'
import dark from '!raw-loader!muse-ui/dist/theme-dark.css'
import carbon from '!raw-loader!muse-ui/dist/theme-carbon.css'
import teal from '!raw-loader!muse-ui/dist/theme-teal.css'
export default {
  name: 'hello',
  data () {
    return {
      theme: 'light',
      themes: {
        light,
        dark,
        carbon,
        teal
      }
    }
  },
  methods: {
    changeTheme (theme) {
      this.theme = theme
      const styleEl = this.getThemeStyle()
      styleEl.innerHTML = this.themes[theme] || ''
    },
    getThemeStyle () {
      const themeId = 'muse-theme'
      let styleEl = document.getElementById(themeId)
      if (styleEl) return styleEl
      styleEl = document.createElement('style')
      styleEl.id = themeId
      document.body.appendChild(styleEl)
      return styleEl
    }
  }
}
</script>

效果图

效果图