iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Vue怎么使用Less与Scss实现主题切换
  • 655
分享到

Vue怎么使用Less与Scss实现主题切换

2023-07-05 06:07:52 655人浏览 泡泡鱼
摘要

这篇文章主要介绍“Vue怎么使用Less与SCSS实现主题切换”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Vue怎么使用Less与Scss实现主题切换”文章能帮助大家解决问题。一、Less/Scs

这篇文章主要介绍“Vue怎么使用Less与SCSS实现主题切换”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Vue怎么使用Less与Scss实现主题切换”文章能帮助大家解决问题。

一、Less/Scss变量换肤

具体实现:

初始化vue项目

安装插件

npm install style-resources-loader -D

npm install vue-cli-plugin-style-resources-loader -D

当然也要安装less、less-loader等插件,具体的安装配置,请自行Google

新建theme.less文件用于全局样式配置。在src目录下新建theme文件夹,在这个文件夹下新建theme.less文件。具体如下:

/src/theme/theme.less// 默认的主题颜色@primaryColor: var(--primaryColor, #000);@primaryTextColor: var(--primaryTextColor, green);// 导出变量:export {  name: "less";  primaryColor: @primaryColor;  primaryTextColor: @primaryTextColor;}

配置vue.config.js文件,实现全局使用变量实现换肤

const path = require("path");module.exports = {  pluginOptions: {    "style-resources-loader": {      preProcessor: "less",      patterns: [        // 这个是加上自己的路径,不能使用(如下:alias)中配置的别名路径        path.resolve(__dirname, "./src/theme/theme.less"),      ],    },  },};

具体的使用:

<template>  <div class="hello">    <p>我是测试文字</p>  </div></template><script>export default {  name: "HelloWorld",};</script><style scoped lang="less">.hello {  p {    color: @primaryTextColor;  }}</style>

备注:如果是用scss也基本同以上用法,只是scss的变量名用&lsquo;$&rsquo;作为前缀,less使用@

至此,我们已经实现了静态更换皮肤,那如何实现动态换肤呢,最重要的就是以下的文件了。

我们可以多配置几种默认主题

在theme文件夹下新建model.js文件,用于存放默认主题

// 一套默认主题以及一套暗黑主题// 一套默认主题以及一套暗黑主题export const themes = {  default: {    primaryColor: `${74}, ${144},${226}`,    primaryTextColor: `${74}, ${144},${226}`,  },  dark: {    primaryColor: `${0},${0},${0}`,    primaryTextColor: `${0},${0},${0}`,  },};

实现动态切换:

在/src/theme文件夹下新建theme.js文件,代码如下:

import { themes } from "./model";// 修改页面中的样式变量值const changeStyle = (obj) => {  for (let key in obj) {    document      .getElementsByTagName("body")[0]      .style.setProperty(`--${key}`, obj[key]);  }};// 改变主题的方法export const setTheme = (themeName) => {  localStorage.setItem("theme", themeName); // 保存主题到本地,下次进入使用该主题  const themeConfig = themes[themeName];  // 如果有主题名称,那么则采用我们定义的主题  if (themeConfig) {    localStorage.setItem("primaryColor", themeConfig.primaryColor); // 保存主题色到本地    localStorage.setItem("primaryTextColor", themeConfig.primaryTextColor); // 保存文字颜色到本地    changeStyle(themeConfig); // 改变样式  } else {    let themeConfig = {      primaryColor: localStorage.getItem("primaryColor"),      primaryTextColor: localStorage.getItem("primaryTextColor"),    };    changeStyle(themeConfig);  }};

切换主题

this.setTheme('dark')

二、element-UI组件的换肤

一般elementUI主题色都有这样一个文件element-variables.scss:

$--color-primary: #1890ff;$--color-success: #13ce66;$--color-warning: #ffba00;$--color-danger: #ff4949;// $--color-info: #1E1E1E;$--button-font-weight: 400;// $--color-text-regular: #1f2d3D;$--border-color-light: #dfe4ed;$--border-color-lighter: #e6ebf5;$--table-border: 1px solid #dfe6ec;$--font-path: "~element-ui/lib/theme-chalk/fonts";@import "~element-ui/packages/theme-chalk/src/index";// the :export directive is the magic sauce for webpack// https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass:export {  theme: $--color-primary;}

main.js中引用

import './styles/element-variables.scss'

在store文件夹下新建settings.js文件,用于页面基础设置

import variables from '@/styles/element-variables.scss'const state = {  theme: variables.theme}const mutations = {  CHANGE_SETTING: (state, { key, value }) => {    // eslint-disable-next-line no-prototype-builtins    if (state.hasOwnProperty(key)) {      state[key] = value    }  }}const actions = {  changeSetting({ commit }, data) {    commit('CHANGE_SETTING', data)  }}export default {  namespaced: true,  state,  mutations,  actions}

一般换肤都是需要有个颜色选择器,用于皮肤设置

在src目录下新建ThemePicker文件夹,新建index.vue文件。

<template>  <el-color-picker    v-model="theme"    :predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"    class="theme-picker"    popper-class="theme-picker-dropdown"  /></template><script>const version = require('element-ui/package.JSON').version // element-ui version from node_modulesconst ORIGINAL_THEME = '#409EFF' // default colorexport default {  data() {    return {      chalk: '', // content of theme-chalk css      theme: ''    }  },  computed: {    defaultTheme() {      return this.$store.state.settings.theme    }  },  watch: {    defaultTheme: {      handler: function(val, oldVal) {        this.theme = val      },      immediate: true    },    async theme(val) {      const oldVal = this.chalk ? this.theme : ORIGINAL_THEME      if (typeof val !== 'string') return      const themeCluster = this.getThemeCluster(val.replace('#', ''))      const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))      console.log(themeCluster, originalCluster)      const $message = this.$message({        message: '  Compiling the theme',        customClass: 'theme-message',        type: 'success',        duration: 0,        iconClass: 'el-icon-loading'      })      const getHandler = (variable, id) => {        return () => {          const originalCluster = this.getThemeCluster(ORIGINAL_THEME.replace('#', ''))          const newStyle = this.updateStyle(this[variable], originalCluster, themeCluster)          let styleTag = document.getElementById(id)          if (!styleTag) {            styleTag = document.createElement('style')            styleTag.setAttribute('id', id)            document.head.appendChild(styleTag)          }          styleTag.innerText = newStyle        }      }      if (!this.chalk) {        const url = `Https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`        await this.getCSSString(url, 'chalk')      }      const chalkHandler = getHandler('chalk', 'chalk-style')      chalkHandler()      const styles = [].slice.call(document.querySelectorAll('style'))        .filter(style => {          const text = style.innerText          return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)        })      styles.forEach(style => {        const { innerText } = style        if (typeof innerText !== 'string') return        style.innerText = this.updateStyle(innerText, originalCluster, themeCluster)      })      this.$emit('change', val)      $message.close()    }  },  methods: {    updateStyle(style, oldCluster, newCluster) {      let newStyle = style      oldCluster.forEach((color, index) => {        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])      })      return newStyle    },    getCSSString(url, variable) {      return new Promise(resolve => {        const xhr = new XMLHttpRequest()        xhr.onreadystatechange = () => {          if (xhr.readyState === 4 && xhr.status === 200) {            this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '')            resolve()          }        }        xhr.open('GET', url)        xhr.send()      })    },    getThemeCluster(theme) {      const tintColor = (color, tint) => {        let red = parseInt(color.slice(0, 2), 16)        let green = parseInt(color.slice(2, 4), 16)        let blue = parseInt(color.slice(4, 6), 16)        if (tint === 0) { // when primary color is in its rgb space          return [red, green, blue].join(',')        } else {          red += Math.round(tint * (255 - red))          green += Math.round(tint * (255 - green))          blue += Math.round(tint * (255 - blue))          red = red.toString(16)          green = green.toString(16)          blue = blue.toString(16)          return `#${red}${green}${blue}`        }      }      const shadeColor = (color, shade) => {        let red = parseInt(color.slice(0, 2), 16)        let green = parseInt(color.slice(2, 4), 16)        let blue = parseInt(color.slice(4, 6), 16)        red = Math.round((1 - shade) * red)        green = Math.round((1 - shade) * green)        blue = Math.round((1 - shade) * blue)        red = red.toString(16)        green = green.toString(16)        blue = blue.toString(16)        return `#${red}${green}${blue}`      }      const clusters = [theme]      for (let i = 0; i <= 9; i++) {        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))      }      clusters.push(shadeColor(theme, 0.1))      return clusters    }  }}</script><style>.theme-message,.theme-picker-dropdown {  z-index: 99999 !important;}.theme-picker .el-color-picker__trigger {  height: 26px !important;  width: 26px !important;  padding: 2px;}.theme-picker-dropdown .el-color-dropdown__link-btn {  display: none;}</style>

在使用ThemePicker组件的位置,去调用vuex中的changeSetting函数

 <theme-picker  @change="themeChange" />import ThemePicker from '@/components/ThemePicker'export default {  components: { ThemePicker },methods:{  themeChange(val) {      this.$store.dispatch('settings/changeSetting', {        key: 'theme',        value: val      })    }}}

关于“Vue怎么使用Less与Scss实现主题切换”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网精选频道,小编每天都会为大家更新不同的知识点。

--结束END--

本文标题: Vue怎么使用Less与Scss实现主题切换

本文链接: https://www.lsjlt.com/news/350018.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Vue怎么使用Less与Scss实现主题切换
    这篇文章主要介绍“Vue怎么使用Less与Scss实现主题切换”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Vue怎么使用Less与Scss实现主题切换”文章能帮助大家解决问题。一、Less/Scs...
    99+
    2023-07-05
  • Vue使用Less与Scss实现主题切换方法详细讲解
    目录一、Less/Scss变量换肤二、element-UI组件的换肤一、Less/Scss变量换肤 具体实现: 1、初始化vue项目 2、安装插件: npm install styl...
    99+
    2023-02-25
    Vue主题切换 Vue Less Scss实现主题切换
  • 使用vue怎么实现主题切换
    这篇文章给大家介绍使用vue怎么实现主题切换,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。第一种办法:动态组件当主题的路由并没有发生变化,仅是组件内部的样式,功能发生了变化,我们可以将一个组件复制一遍,修改完后,通过懒...
    99+
    2023-06-15
  • Vue怎么用CSS变量实现切换主题功能
    本篇内容介绍了“Vue怎么用CSS变量实现切换主题功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!  ...
    99+
    2024-04-02
  • 使用vue-antd动态切换主题
    目录vue-antd动态切换主题安装依赖Vue3.0 + Antd,修改antd主题色,配置全局cssvue-antd动态切换主题 安装依赖 1 webpack-theme-colo...
    99+
    2024-04-02
  • vue+element-ui实现主题切换功能
    element-ui提供了自定义主题 自定义主题 一、安装 npm i element-theme -gnpm i element-theme-chalk -Dnpm i https...
    99+
    2024-04-02
  • Vue UI框架的主题切换功能实现
    目录AntD 的方式1. 创建黑暗主题文件2. 创建切换主题的函数3. 切换主题Quasar 的方式ElementUI 的方式NaiveUI 的方式在如今,很多网页已经可以手动切换明...
    99+
    2022-12-08
    vue主题切换 vue ui框架主题切换
  • 怎么简单实现CSS主题的切换
    这篇文章给大家分享的是有关怎么简单实现CSS主题的切换的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。HTML首先,我们需要包含“按钮”,这些按钮将触发主题根据选择的主题进行切换。(注:你总是可以使这些作为 opt...
    99+
    2023-06-08
  • 怎么解决使用vue-router与v-if实现tab切换遇到的问题
    这篇文章主要介绍怎么解决使用vue-router与v-if实现tab切换遇到的问题,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!先上代码,用两种方式实现的效果使用vue-router...
    99+
    2024-04-02
  • vue实现主题切换的多种思路分享
    目录动态改变主题 第一种办法:动态组件 第二种办法,路由隔离 总结 额外补充基于css的两种方法方法一 多套css方法二 scss动态切换变量 动态改变主题 首先需要解决的是如何知...
    99+
    2024-04-02
  • Vue项目如何实现切换主题色思路
    目录Vue项目切换主题色思路需求实现效果实现思路总结Vue项目切换主题色思路 需求 用户通过取色器选择自己喜欢的颜色,替换项目中的主题色 实现效果 实现思路 在项目中使用的是les...
    99+
    2023-01-13
    Vue主题色 Vue切换主题色 Vue主题色切换
  • 利用JetpackCompose实现主题切换功能
    目录前言color.ktTheme.kt关于compositionLocalOf完整代码前言 新建的Compose项目默认的 Material 主题为我们提供了一...
    99+
    2024-04-02
  • vue怎么实现更换主题功能
    这篇文章主要讲解了“vue怎么实现更换主题功能”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue怎么实现更换主题功能”吧!方式一:class切换方式实现:在每个需要更换的页面定义多个cla...
    99+
    2023-07-04
  • WinForm中怎么实现主题和皮肤切换
    在WinForm中实现主题和皮肤切换通常可以通过以下步骤来实现: 创建多个不同主题或皮肤的样式文件,比如XML文件或INI文件等,...
    99+
    2024-04-08
    winform
  • MySQL主从切换怎么实现
    这篇文章主要介绍“MySQL主从切换怎么实现”,在日常操作中,相信很多人在MySQL主从切换怎么实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”MySQL主从切换怎么实现”的疑惑有所帮助!接下来,请跟着小编...
    99+
    2023-07-02
  • 怎么使用Vue实现一个tab栏切换功能
    本篇内容介绍了“怎么使用Vue实现一个tab栏切换功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一、创建Vue项目首先需要安装Vue C...
    99+
    2023-07-05
  • vue怎么实现动态切换class
    本篇内容介绍了“vue怎么实现动态切换class”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!文件内容----//为item添加不存在的属性...
    99+
    2023-07-04
  • mysql主备自动切换怎么实现
    要实现MySQL主备自动切换,可以使用MySQL Replication和MySQL Cluster来实现高可用性。以下是一种实现方...
    99+
    2024-04-09
    mysql
  • 使用vue怎么实现一个用户登录切换功能
    今天就跟大家聊聊有关使用vue怎么实现一个用户登录切换功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。Vue的优点Vue具体轻量级框架、简单易学、双向数据绑定、组件化、数据和结构的...
    99+
    2023-06-14
  • 怎么用vue实现导航菜单切换效果
    这篇文章主要介绍“怎么用vue实现导航菜单切换效果”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“怎么用vue实现导航菜单切换效果”文章能帮助大家解决问题。具体代码如下css*{  ...
    99+
    2023-07-04
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作