手机医疗网站,怎样进行站点优化,西安网络运营公司有哪些,搜索引擎优化免费Vue3 Scss 实现主题切换效果
先给大家看一下主题切换的效果#xff1a;
像这样的效果实现起来并不难#xff0c;只是比较麻烦#xff0c;目前我知道的有两种方式可以实现#xff0c;分别是 CSS 变量、样式文件切换#xff0c;下面是该效果的核心实现方法
CSS变量
给…
Vue3 Scss 实现主题切换效果
先给大家看一下主题切换的效果
像这样的效果实现起来并不难只是比较麻烦目前我知道的有两种方式可以实现分别是 CSS 变量、样式文件切换下面是该效果的核心实现方法
CSS变量
给需要变化的样式设置 css 变量然后可以通过 js 的 document.documentElement.style.setProperty 方法来修改 css 变量的值从而实现主题切换的效果
script setup langts
import { ref } from vue;const $css document.documentElement.style
const is refboolean(false)const btn () {is.value !is.valueis.value ? $css.setProperty(--color, #000) : $css.setProperty(--color, #fff)
}
/scripttemplatediv classbox/divbutton clickbtn按钮/button
/templatestyle langscss
$color: var(--color, #fff);.box {width: 200px;height: 200px;background-color: $color;transition: all 0.3s;
}
/style该方式适合应用于简单的切换场景如果页面比较复杂使用该方式会导致使用大量的 css 变量而且写法也会很麻烦
这时候推荐使用下面这种方式
样式文件切换
该方式核心思想就是定义两套样式通过 js 控制两套样式的切换从而实现该效果
动态加载局部样式
先准备好两个 Scss 主题样式文件
// light.scss
.container{background-color: #fff;
}// dark.scss
.container{background-color: #000;
}然后在 App.vue 中引入
script setup langts
import Theme from /view/Theme.vue
/scripttemplateTheme /
/templatestyle langscss
.light {import /styles/light.scss;
}.dark {import /styles/dark.scss;
}
/style在 Theme.vue 中编写布局通过动态类名来实现主题切换功能
script setup langts
import { ref } from vue;const is ref(false)
/scripttemplatediv :classis ? light : darkdiv classcontainer/div/divbutton clickis !is切换主题/button
/templatestyle scoped langscss
.container {width: 300px;height: 300px;transition: all 0.3s;
}
/style修改link标签样式路径
直接在项目的 index.html 中通过 link 引入样式文件
!DOCTYPE html
html langenheadmeta charsetUTF-8 /link relicon typeimage/svgxml href/vite.svg /meta nameviewport contentwidthdevice-width, initial-scale1.0 /titleVite Vue TS/title!-- 在这里先定义一个默认的样式 --link relstylesheet href./src/styles/light.scss titlelight/headbodydiv idapp/divscript typemodule src/src/main.ts/script/body
/html
在 src/App.vue 中获取 link 标签并通过逻辑让他切换样式文件从而实现主题切换效果
script setup langts
import { ref } from vue;// 获取link标签
const links document.querySelectorAll(link)const is refboolean(false)const btn () {is.value !is.value// 目前只有两个link标签所以这里直接写死只展示核心代码is.value ? links[1].href ./src/styles/dark.scss : links[1].href ./src/styles/light.scss
}
/scripttemplatediv classcontainer/divbutton clickbtn按钮/button
/templatestyle scoped langscss
.container {width: 300px;height: 300px;transition: all 0.3s;
}
/style