原文:https://medium.com/js-dojo
作者:Sunil Joshi

微信搜寻【前端全栈开发者】关注这个脱发、摆摊、卖货、继续学习的程序员,第一工夫浏览最新文章,会优先两天发表新文章。关注即可大礼包,准能为你节俭不少钱!

在本文中,我将在不应用任何库的状况下将darkLight模式性能实现到咱们的Vue Vite应用程序中。

咱们将首先创立一个简略的Vite应用程序,而后为咱们的应用程序设置一个简略的用户界面。在创立咱们的Vue应用程序之前,我想提到WrapPixel提供的一些很棒的收费Vue模板,它们能够收费下载并用于集体和商业用途。他们能够节俭你的工夫,因为你能够间接在你的我的项目中应用他们令人惊叹的用户界面,这将给你的应用程序带来惊人的外观和感觉,所以肯定要去看看。

创立一个Vuejs Vite应用程序

要设置Vite应用程序,请关上您的终端并输出以下内容:

npm init vite-app themeswitcher

这个命令将搭建一个新的vite应用程序,而后进入我的项目目录装置我的项目依赖项:

cd themeswitchernpm install

装置后,咱们当初能够应用 npm run dev 命令运行咱们的应用程序:

code . && npm run dev

code . 命令将以VS Code关上咱们的应用程序。

咱们的应用程序当初将在端口3000上运行。

随着应用程序的启动和运行,咱们当初能够创立CSS。在 public 目录内创立一个 css/dark.css 文件,这是咱们将在光明模式环境中存储所有CSS代码的中央。

在dark.css文件中增加以下代码:

:root {  --text: #ffffff;  --background: #1d1d23;}body {  background-color: var(--background) !important;}h1,h2,h3,h4,h5,h6,p,small,a {  color: var(--text) !important;}

当初将在head中创立一个link标签将其设置为咱们创立的 dark.css 文件,以便能够利用在此定义的所有款式。

咱们将应用Javascript类来执行此操作,在src目录中创立 src/theme.js 文件,并增加以下代码:

export default class themeChanger {    /**     * @constructor     */    constructor() {}    _addDarkTheme() {        const darkThemeLinkEl = document.createElement('link')        darkThemeLinkEl.setAttribute('rel', 'stylesheet')        darkThemeLinkEl.setAttribute('href', './css/dark.css')        darkThemeLinkEl.setAttribute('id', 'dark-theme-style')        const docHead = document.querySelector('head')        docHead.append(darkThemeLinkEl)    }    _removeDarkTheme() {        const darkThemeLinkEl = document.querySelector('#dark-theme-style')        const parentNode = darkThemeLinkEl.parentNode        parentNode.removeChild(darkThemeLinkEl)    }    _darkThemeSwitch() {        const darkThemeLinkEl = document.querySelector('#dark-theme-style')        if (!darkThemeLinkEl) {            this._addDarkTheme()        } else {            this._removeDarkTheme()        }    }}

咱们创立3种办法:

  • _addDarkTheme():这会将link标签增加到应用程序的HTML head中。
  • _removeDarkTheme():这将删除已增加到HTML head的link标签。
  • _darkThemeSwitch():这将切换增加和删除办法,以在咱们的HTML head中增加和删除link标签。

咱们能够持续在Vue.js组件中应用此办法。

编辑 components/HelloWorld.vue 中的代码,如下所示:

<template>  <h3>Vite is the future of Frontend Developement.</h3>  <small>Thanks to Evan You</small>  <br />  <button @click="darkThemeSwitch">switch</button></template><script>import themeChanger from "../util/theme.js";export default {  name: "HelloWorld",  props: {    msg: String,  },  data() {    return {      themeChanger: null,    };  },  methods: {    darkThemeSwitch() {      this.themeChanger._darkThemeSwitch();    },  },  created() {    this.themeChanger = new themeChanger();  },};</script>

咱们引入 themeChanger 类的实例,而后将其存储在Vue.js data实例中。而后,咱们创立一个按钮,该按钮将调用咱们在 theme.js 文件中创立的 _darkThemeSwitch

实现此操作后,咱们当初能够在应用程序中在明暗模式之间切换。