【vite-vue】demo项目创建

在日常开发中,我们常常会创建demo去测试我们封装的组件或者页面是否达到了预期的效果,但是这些demo通常会在测试后就删除。

为了便于日后遇到同样的问题能找到对应的demo,今天我们就来封装一个vite-vue的demo项目。

项目要点:

  1. 确保每个demo页之间的样式隔离
  2. home页面存在路由,便于导航

初始化demo项目

powershell 复制代码
npm create vite@latest 

项目结构

路径别名配置

配置路径别名,提升代码可维护性,降低输入成本。

ts 复制代码
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

// https://vite.dev/config/
export default defineConfig({
  resolve:{
    alias: {
      '@' : path.resolve(__dirname,'src')
    }
  },
  plugins: [
    vue()
  ],
})
json 复制代码
// tsconfig.app.json
{
  "extends": "@vue/tsconfig/tsconfig.dom.json",
  "compilerOptions": {
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "erasableSyntaxOnly": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedSideEffectImports": true,
    "paths": {
      "@/*":["./src/*"] //配置
    }
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}

页面路由配置

ts 复制代码
// router/index.ts
import { createRouter, createWebHistory, type RouteLocationRaw, type RouteRecordRaw } from 'vue-router'

export const routes:RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/home.vue'),
    meta: {
      title: 'home page'
    }
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('@/views/demo-pages/test/test.vue'),
    meta: {
      title: 'test demo page'
    }
  }, 
]

export const router = createRouter({
  history: createWebHistory(),
  routes
})

export const routerPush = (to: RouteLocationRaw | string): void => {
  router.push(typeof to === 'string' ? {path:to} : to)
}

export const currentPageTitle =  ()=>{
  const title = router.currentRoute.value.meta.title
  return title ? title : ''
}

创建home页面,并将所有路由导航添加到该页面

vue 复制代码
// home.vue
<script lang="ts" setup>
import { routerPush, routes } from '@/router';
</script>
<template>
  <div>
    <ul>
      <li v-for="route in routes" :key="route.name" @click="routerPush(route.path)">{{ route.name }}</li>
    </ul>
  </div>
</template>
vue 复制代码
// app.vue
<script lang="ts" setup>
import { currentPageTitle } from './router';

</script>
<template>
  <div>
    <h1>{{ currentPageTitle() }}</h1>
    <RouterView></RouterView>
  </div>
</template>

效果

项目地址(github.com/ALiuYiLin/1...)

相关推荐
崔庆才丨静觅9 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606110 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了10 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅10 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅11 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅11 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment11 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅11 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊11 小时前
jwt介绍
前端
爱敲代码的小鱼11 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax