【问题标题】:Change Vuetify Theme according to API Request Response根据 API 请求响应更改 Vuetify 主题
【发布时间】:2021-09-04 12:47:27
【问题描述】:

我想知道是否可以根据 API 请求响应更改主题颜色? 我需要这样做,因为我希望管理员为其应用程序的所有用户选择主题。 我已经在 vuetify.js 文件和请求方法上创建了主题对象。现在我只需要根据 api 请求值以某种方式更改选择的主题。这可能吗?

【问题讨论】:

标签: vue.js vuetify.js vuex


【解决方案1】:

您可以直接在$vuetify 对象中设置theme 属性,它会更新当前的渲染主题。

// Within a vue component / plugin

const newLightTheme = await axios.get('/api/theme')
// Programatically update light theme
this.$vuetify.theme.themes.light = newLightTheme
// Same for dark
this.$vuetify.theme.themes.dark = newDarkTheme

// Also work with property within a theme
this.$vuetify.theme.themes.light.primary = '#123456'

一个很好的阅读来源:https://betterprogramming.pub/changing-application-theme-dynamically-in-vuetify-js-c01d640699c4

【讨论】:

    【解决方案2】:

    您可以通过 2 种不同的方法来实现。

    方法一: 1.2 支持 CSS 变量 a.k.a customProperties。您必须在 Vuetify 配置中启用 customProperties。这将生成 css 变量,您可以在样式表中使用它们。这些值也可以使用 javascript 动态分配。可以参考here。

    Vue.use(Vuetify, {
     options: {
       customProperties: true
     }
    })
    

    方法二: 在 main.js 文件中,在启动 vuetify 之前,可以从 API 中点击获取主题,然后进行初始化。

    import Vue from 'vue';
    import Vuetify from 'vuetify/lib';
    
    Vue.use(Vuetify);
    
    const renderApp = async () => {
      const { theme } = await api.getTheme();
      const vuetify = new Vuetify({
        theme,
      });
    
      new Vue({
        vuetify,
      }).$mount('#app');
    };
    
    renderApp();
    

    【讨论】:

    • 第二种方法对我来说有点工作,但它不允许我使用 await 关键字,因为我得到了一个承诺。你知道如何使 vuetify.js 异步吗?谢谢
    • 有没有办法在 vuetify.js 而不是 main.js 中制作这个?我正在将 vuetify 导出到 vuetify.js 中的 main.js,并且那里我需要异步运行 api 请求。
    • 您可以在启动后尝试这样更新。 this.$vuetify.theme.themes.light=theme.
    • 这在 vuetify.js 中也不起作用。什么都没有发生
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2021-03-31
    • 2013-07-14
    • 2012-11-24
    • 2014-02-14
    • 2020-04-14
    相关资源
    最近更新 更多