用户可切换的自定义主题与Vue.js

use*_*554 6 themes vue.js vuejs2

我有一个VueJS应用程序,它将有许多不同的主题(至少20左右).每个主题样式表不仅会更改颜色和字体大小等内容,还会更改某些元素的位置和布局.

我希望用户能够动态地在这些主题之间切换.因此,在运行时,用户将能够打开"选项"菜单并从下拉列表中进行选择.

在VueJS中拥有许多动态用户可选主题的最简洁方法是什么?


我想过几个方面,比如:

  • 动态插入<link><style>标记.虽然这可能有用,但我并不认为它特别"干净",如果我从AJAX加载,那么我经常会看到一个FOUC.
  • 只需通过计算属性更改Vue类绑定即可.类似于if-else为每个组件中的每个受支持主题建立链.我并不特别喜欢这个解决方案,因为每次我添加新主题时,我制作的每个组件都需要更新.

在React中,我认为有一个插件或具有<ThemeProvider>组件的东西,其中添加主题就像包装它一样简单,即<ThemeProvider theme={themeProp}><MyComponent></ThemeProvider>,该主题中的所有样式将应用于该组件和所有子组件.

VueJS有类似的东西,还是有办法实现它?

Con*_*oad 13

我承认我对这个有一些乐趣.该解决方案不依赖于Vue的,但它可以很容易地通过使用 Vue公司.开始了!

我的目标是创建一个"特别干净"的动态插入<link>样式表,这不应该导致FOUC.

我创建了一个类(技术上,它是一个构造函数,但你知道我的意思)调用ThemeHelper,它的工作方式如下:

  • myThemeHelper.add(themeName, href)将从href(URL)预加载样式表stylesheet.disabled = true,并为其命名(仅用于跟踪它).这将返回一个在调用样式表时Promise解析为CSSStyleSheetonload内容.
  • myThemeHelper.theme = "<theme name>"(setter)选择要应用的主题.禁用上一个主题,并启用给定主题.由于样式表已经预先加载,因此切换很快就会发生.add.
  • myThemeHelper.theme (getter)返回当前主题名称.

班级本身是33行.我制作了一个在一些Bootswatch主题之间切换的片段,因为那些CSS文件相当大(100Kb +).

const ThemeHelper = function() {
 
  const preloadTheme = (href) => {
    let link = document.createElement('link');
    link.rel = "stylesheet";
    link.href = href;
    document.head.appendChild(link);
    
    return new Promise((resolve, reject) => {
      link.onload = e => {
        const sheet = e.target.sheet;
        sheet.disabled = true;
        resolve(sheet);
      };
      link.onerror = reject;
    });
  };
  
  const selectTheme = (themes, name) => {
    if (name && !themes[name]) {
      throw new Error(`"${name}" has not been defined as a theme.`); 
    }
    Object.keys(themes).forEach(n => themes[n].disabled = (n !== name));
  }
  
  let themes = {};

  return {
    add(name, href) { return preloadTheme(href).then(s => themes[name] = s) },
    set theme(name) { selectTheme(themes, name) },
    get theme() { return Object.keys(themes).find(n => !themes[n].disabled) }
  };
};

const themes = {
  flatly: "https://bootswatch.com/4/flatly/bootstrap.min.css",
  materia: "https://bootswatch.com/4/materia/bootstrap.min.css",
  solar: "https://bootswatch.com/4/solar/bootstrap.min.css"
};

const themeHelper = new ThemeHelper();

let added = Object.keys(themes).map(n => themeHelper.add(n, themes[n]));

Promise.all(added).then(sheets => {
  console.log(`${sheets.length} themes loaded`);
  themeHelper.theme = "materia";
});
Run Code Online (Sandbox Code Playgroud)
<h3>Click a button to select a theme</h3>

<button 
  class="btn btn-primary" 
  onclick="themeHelper.theme='materia'">Paper theme
  </button>
  
<button 
  class="btn btn-primary" 
  onclick="themeHelper.theme='flatly'">Flatly theme
</button>

<button 
  class="btn btn-primary" 
  onclick="themeHelper.theme='solar'">Solar theme
</button>
Run Code Online (Sandbox Code Playgroud)

不难说我完全是关于ES6(也许我过度使用const了:)

就Vue而言,你可以创建一个包含以下内容的组件<select>:

const ThemeHelper = function() {
 
  const preloadTheme = (href) => {
    let link = document.createElement('link');
    link.rel = "stylesheet";
    link.href = href;
    document.head.appendChild(link);
    
    return new Promise((resolve, reject) => {
      link.onload = e => {
        const sheet = e.target.sheet;
        sheet.disabled = true;
        resolve(sheet);
      };
      link.onerror = reject;
    });
  };
  
  const selectTheme = (themes, name) => {
    if (name && !themes[name]) {
      throw new Error(`"${name}" has not been defined as a theme.`); 
    }
    Object.keys(themes).forEach(n => themes[n].disabled = (n !== name));
  }
  
  let themes = {};

  return {
    add(name, href) { return preloadTheme(href).then(s => themes[name] = s) },
    set theme(name) { selectTheme(themes, name) },
    get theme() { return Object.keys(themes).find(n => !themes[n].disabled) }
  };
};

let app = new Vue({
  el: '#app',
  data() {
    return {
      themes: {
        flatly: "https://bootswatch.com/4/flatly/bootstrap.min.css",
        materia: "https://bootswatch.com/4/materia/bootstrap.min.css",
        solar: "https://bootswatch.com/4/solar/bootstrap.min.css"
      },
      themeHelper: new ThemeHelper(),
      loading: true,
    }
  },
  created() {
    // add/load themes
    let added = Object.keys(this.themes).map(name => {
      return this.themeHelper.add(name, this.themes[name]);
    });

    Promise.all(added).then(sheets => {
      console.log(`${sheets.length} themes loaded`);
      this.loading = false;
      this.themeHelper.theme = "flatly";
    });
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.2/dist/vue.js"></script>

<div id="app">
  <p v-if="loading">loading...</p>

  <select v-model="themeHelper.theme">
    <option v-for="(href, name) of themes" v-bind:value="name">
      {{ name }}
    </option>
  </select>
  <span>Selected: {{ themeHelper.theme }}</span>
</div>

<hr>

<h3>Select a theme above</h3>
<button class="btn btn-primary">A Button</button>
Run Code Online (Sandbox Code Playgroud)

我希望这对你有用,因为它对我来说很有趣!