返回

极简入门:Vue3 + Tailwind CSS + NutUI打造便捷主题切换侧边栏

前端

Vue3、Tailwind CSS 和 NutUI 携手打造强劲主题切换侧边栏

构建项目

踏入前端技术的风暴之眼,掌握技术风向至关重要。Vue3、Tailwind CSS 和 NutUI 作为当今最炙手可热的工具,无疑是打造强劲项目的最佳拍档。让我们踏上开发之旅,运用这三位前端利器的力量,打造一个优雅的主题切换侧边栏,让你的前端项目脱颖而出。

首先,使用 Vue3 脚手架创建项目:

vue create <项目名称>

按照提示配置项目,然后安装必要的依赖项:

npm install tailwindcss @nutui/nutui

在项目根目录下创建 tailwind.config.js 文件:

module.exports = {
  content: ["./index.html", "./src/**/*.{vue,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

配置项目

在 package.json 文件中添加以下脚本:

"scripts": {
  "build": "vue-tsc --noEmit && rollup -c",
  "dev": "vue-tsc --watch --noEmit && rollup -c -w",
  "lint": "eslint src/**/*.{js,vue}"
}

开发主题切换侧边栏

现在,让我们进入激动人心的部分——开发主题切换侧边栏。

在项目根目录下创建 App.vue 文件,添加如下代码:

<template>
  <div id="app">
    <NutButton size="mini" type="primary" @click="toggleTheme">切换主题</NutButton>
    <div class="theme-content">
      <h1>你好,世界!</h1>
    </div>
  </div>
</template>

<script>
import { useTheme } from "./theme";

export default {
  setup() {
    const { toggleTheme } = useTheme();
    return { toggleTheme };
  },
};
</script>

在项目根目录下创建 theme.js 文件,添加如下代码:

import { createPinia, defineStore } from "pinia";
import { reactive, onMounted, ref } from "vue";

const store = createPinia();

export const useTheme = defineStore("theme", () => {
  const theme = reactive({
    dark: false,
  });

  const toggleTheme = () => {
    theme.dark = !theme.dark;
  };

  onMounted(() => {
    // ...
  });

  return { theme, toggleTheme };
});

在项目根目录下创建 style.css 文件,添加如下代码:

body {
  margin: 0;
  font-family: "Helvetica", "Arial", sans-serif;
}

.theme-content {
  padding: 20px;
  background-color: #fff;
}

.dark-theme {
  background-color: #222;
  color: #fff;
}

运行项目

最后,运行以下命令启动项目:

npm run dev

你将看到一个主题切换侧边栏,尽情探索其功能吧!

总结

本文循序渐进地介绍了如何利用 Vue3、Tailwind CSS 和 NutUI 开发一个主题切换侧边栏。通过掌握这些工具的基本使用,你将具备打造更复杂 Vue3 应用的能力,在前端世界中大展身手。

常见问题解答

  • 为什么使用 Vue3? Vue3 是一个现代化的 JavaScript 框架,提供了强大的响应式和组合式 API。
  • Tailwind CSS 有什么优势? Tailwind CSS 是一种实用的 CSS 框架,提供了一组可重用的效用类,可以快速、轻松地创建一致的 UI。
  • NutUI 是什么? NutUI 是一个移动端组件库,提供了丰富的现成组件,可以加速开发过程。
  • 如何自定义主题? 你可以在 style.css 文件中编辑 CSS 规则来定制主题的外观。
  • 如何部署主题切换侧边栏? 你可以使用诸如 Netlify 或 Vercel 等平台来部署你的应用程序,以便在网络上访问。