zoukankan      html  css  js  c++  java
  • uniapp设置不同的主题(Theme)

    App.vue:

    <style lang="stylus">
    
    @css {
    html {
      --primary: blue;
      --bg-image: url(https://i.loli.net/2020/10/14/gQq96O4DxRVXSKP.jpg);
    }
    html[data-theme='green'] {
     --primary: green;
      --bg-image: url(https://i.loli.net/2020/10/14/KdraGmYFC8Wpsz5.jpg);
    }
    html[data-theme='pink'] {
     --primary: pink;
     --bg-image: url(https://i.loli.net/2020/10/14/O4wUuGvM3Cdjl16.jpg);
    }
    }
    
    </style>
    

    组件中使用主题和切换主题:

    <template>
      <view class="content">
        <view class="title"><text>hello world</text></view>
        <button type="default" @click="changeTheme(1)">theme blue</button>
        <button type="default" @click="changeTheme(2)">theme green</button>
        <button type="default" @click="changeTheme(3)">theme pink</button>
      </view>
    </template>
    
    <script>
    export default {
      data() {
        return {};
      },
      methods: {
        changeTheme(id) {
          if (id == 1) {
            document.documentElement.removeAttribute('data-theme');
          } else if (id == 2) {
            document.documentElement.setAttribute('data-theme', 'green');
          } else if (id == 3) {
            document.documentElement.setAttribute('data-theme', 'pink');
          }
        }
      }
    };
    </script>
    
    <style lang="stylus">
    .content
      min-height 100vh
      background-image unquote('var(--bg-image)')
    .title
      color unquote('var(--primary)')
    </style>
    

    或者这样

    App.vue:

    <style lang="stylus">
    @css {
    .theme {
      --primary: red;
    }
    .theme[data-theme='green'] {
     --primary: green;
    }
    .theme[data-theme='pink'] {
     --primary: pink;
    }
    }
    </style>
    

    组件中使用

    <template>
      <view class="theme content" :data-theme="theme">
        <view class="title"><text>hello world</text></view>
        <button type="default" @click="changeTheme(1)">theme blue</button>
        <button type="default" @click="changeTheme(2)">theme green</button>
        <button type="default" @click="changeTheme(3)">theme pink</button>
      </view>
    </template>
    
    <script>
    export default {
      data() {
        return {
          theme: ''
        };
      },
      methods: {
        changeTheme(id) {
          if (id == 1) {
            this.theme = '';
          } else if (id == 2) {
            this.theme = 'green';
          } else if (id == 3) {
            this.theme = 'pink';
          }
        }
      }
    };
    </script>
    
    <style lang="stylus" scoped>
    .title
      color unquote('var(--primary)')
    </style>
    

    See also:

  • 相关阅读:
    同样的代码bug
    Vim中的Tab
    在Vue中同时使用过渡和动画
    在Vue中使用animate.css
    Vue中的css动画
    动态组件与v-once指令
    在Vue中使用插槽
    非父子组件间的传值
    给组件绑定原生事件
    组件参数校验和非props特性
  • 原文地址:https://www.cnblogs.com/ajanuw/p/13914782.html
Copyright © 2011-2022 走看看