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

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

What is the cleanest way to have many dynamic user-selectable themes in VueJS?


我想到了几种方法,比如:

  • 动态插入<link><style>标签.虽然这可能有效,但我并不认为它特别"干净",如果我从AJAX加载,那么通常我会看到FOUC.
  • 只需通过计算(computed)属性更改Vue类绑定.比如每个组件中每个支持的主题都有一个if-else链.我并不特别喜欢这个解决方案,因为这样一来,我制作的每个组件都需要在以后每次添加新主题时进行更新.

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

VueJS是否有类似的功能,或者有没有实现的方法?

推荐答案

我承认我在这件事上玩得很开心.此解决方案在Vue上不支持depend,但在Vue上可以轻松使用by.开始!

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

我创建了一个名为ThemeHelper的类(从技术上讲,它是一个构造函数,但你知道我的意思),其工作原理如下:

  • myThemeHelper.add(themeName, href)将从href(一个URL)和stylesheet.disabled = true预加载一个样式表,并给它一个名称(只是为了跟踪它).当调用样式表的onload时,返回一个解析为CSSStyleSheetPromise.
  • myThemeHelper.theme = "<theme name>"(setter) Select 要应用的主题.上一个主题被禁用,而给定的主题被启用.切换发生得很快,因为.add已经预加载了样式表.
  • myThemeHelper.theme(getter)返回当前主题名.

这门课本身有33行.我制作了一个片段,在一些 bootstrap 样本主题之间切换,因为这些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";
});
<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>

不难看出我完全是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";
    });
  }
});
<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>

我希望这对你有用,对我来说也很有趣!

Vue.js相关问答推荐

如何在AXIOS调用响应中动态导入视频并创建它的绝对路径?

视图中的 vue 样式不适用于 html

将 v-calendar 与以时间和日期格式出现的事件一起使用

Vue.js 3 运行时挂载组件实例

如果单元格不可见,则以编程方式打开行的编辑模式. Ag 网格,Vue.js

Vue 和 Nuxt 之间生命周期钩子的不同行为

带有热重载的 docker 容器上的 Vue.js 应用程序

如何在 vuejs 自定义指令中传递动态参数

Vue index.html favicon 问题

eslint – 如何知道 defined定义规则的位置

Vuejs在复选框 Select 上切换div可见性

Vue 和 TypeScript 所需的props

Vue.js:从 parent父Vue 获取数据

Vuetify v-btn 路由活动类问题

Vue路由在新页面上回到顶部

Vuejs获取事件正在调用的元素?

Vuejs 不会在 HTML 表格元素中呈现组件

v-for 中的计算(Computed)/动态(Dynamic) v-model 名称

如何访问通用 javascript 模块中的当前路由元字段

Vue-meta:metaInfo 无权访问计算(computed)属性