[vue3+vite+tsx] Detailed process of project construction

Table of contents

  1. Environmental requirements
  2. Vite + Vue3 build initialization
  3. Routing Router installation and configuration
  4. Configure tsx support
  5. Installation and use of less
  6. Unified introduction of styles
  7. Installation and use of ElementUI
  8. vite configuration path alias
  9. i18n configuration multilingual
  10. Design the Layout UI of the system
  11. Design menu bar + permission control
  12. Design API Directory
  13. configure mock
  14. Function page writing

1. Environmental requirements

  • node : Node.js version >= 12.0.0, currently used version: v14.16.0
  • Package management tool: npm/yarn, currently using yarn: v1.22.10
  • Editor: VSCode

2. Vite + Vue3 build initialization

  1. Install vite globally
yarn global add vite


# 安装vite+vue3.0项目,Vite 需要 Node.js 版本 >= 12.0.0。
D:/
# 基于vite搭建项目,项目名:rbac-manage,前端框架使用vue,开发语言:typescript
yarn create vite
# √ Project name: ... rbac-manage
# √ Select a framework: » vue
# √ Select a variant: » vue-ts

# 切换工作目录到rbac-manage,
cd rbac-manage
# 下载项目运行的前端依赖模块
  1. Build a project based on vite, project name: rbac-manage, front-end framework uses vue3, development language: TypeScript
yarn create vite

# √ Project name: ... rbac-manage
# √ Select a framework: » vue
# √ Select a variant: » vue-ts
  1. Startup project
# 切换工作目录到rbac-manage
cd rbac-manage
# 下载项目运行的前端依赖模块
yarn
# 启动测试服务器,运行vue项目
yarn dev

So far, a Vue3 project built by Vite has been built, supporting TypeScript syntax.

3. Installation and configuration of Router

  1. Install vue-router 4.x
yarn add vue-router@next
  1. Configure the routing module

create src/router/index.ts, code:

import {
    
    createRouter, Router, createWebHistory, RouteRecordRaw} from 'vue-router'

// 路由列表
const routes:Array<RouteRecordRaw> = [
  // 省略,见项目src/router/index.ts具体代码
]

const router:Router = createRouter({
    
    
  // history, 指定路由的模式
  history: createWebHistory(),
  // 路由列表
  routes,
});

export default router

According to the module division of the project, the design project directory and project routing are as follows:

  • Create src/viewsa directory, and then add login directory, member directory, device directory, operator directory, point-group directory, scenario directory, wbs directory, add Index.vue file to each directory as the entry file of each module, as shown below:
  • Update src/router/index.tsthe router in the project routing as follows:
const routes: Array<RouteRecordRaw> = [
  {
    
    
    name: "index",
    path: "/",
    redirect: "/member",
  },
  {
    
    
    name: "Login",
    path: "/login",
    component: () => import("../views/login/Index.vue"),
  },
  {
    
    
    name: "Member",
    path: "/member",
    component: () => import("../views/member/Index.vue"),
  },
  {
    
    
    name: "Device",
    path: "/device",
    component: () => import("../views/device/Index.vue"),
  },
  {
    
    
    name: "Operator",
    path: "/operator",
    component: () => import("../views/operator/Index.vue"),
  },
  {
    
    
    name: "PointGroup",
    path: "/point-group",
    component: () => import("../views/point-group/Index.vue"),
  },
  {
    
    
    name: "Scenario",
    path: "/scenario",
    component: () => import("../views/scenario/Index.vue"),
  },
  {
    
    
    name: "Wbs",
    path: "/wbs",
    component: () => import("../views/wbs/Index.vue"),
  },
];
  • Introduce router.ts into the project

In src/main.tsthe file, register the router object into the project

import {
    
     createApp } from "vue";
import App from "./App.vue";
import router from "./router";

createApp(App).use(router).mount("#app");

In src/App.vuethe component, add the content corresponding to the display route:

<template>
  <router-view />
</template>

<script setup lang="ts"></script>

At this point, the construction of the project routing switch is completed.

4. Configure tsx support

Documentation: https://cn.vitejs.dev/guide/features.html#jsx

  1. install plugin
yarn add -D @vitejs/plugin-vue-jsx
  1. configurationvite.config.ts
import {
    
     defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";

// https://vitejs.dev/config/
export default defineConfig({
    
    
  plugins: [vue(), vueJsx({
    
    })],
});
  1. Configure tsconfig.json
{
    
    
  "compilerOptions": {
    
    
    "jsx": "preserve",
    "jsxFactory": "h",
    "jsxFragmentFactory": "Fragment"
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
  1. test vue3 + tsx

Create a TestDemo.tsx file in the components directory and reference it in the page to test whether the tsx file is parsed successfully:

import {
    
     FunctionalComponent as FC, defineComponent, reactive, onMounted } from 'vue';

// 无状态组件
const FcNode: FC<{
    
     data: number }> = ({
    
     data }) => {
    
    
  return (
    <>
      <hr />
      <div>子组件:
        {
    
    data < 10 ? <span>{
    
    data}</span> : <h1>{
    
    data}</h1>}
      </div>
    </>
  )
};

// 状态组件需要使用 defineComponent
export default defineComponent({
    
    
  name: 'TsxDemo',
  setup() {
    
    
    const data = reactive({
    
     count: 0 });

    onMounted(() => {
    
    
      data.count = 5;
    });

    const clickHandler = () => data.count++

    return () => (
      <>
        <span style={
    
    {
    
     marginRight: '10px' }}>{
    
     data.count }</span>
        <button onClick={
    
    clickHandler}>+</button>
        <FcNode data={
    
    data.count}/>
      </>
    )
  }
})

So far, the configuration of tsx has been completed.

5. Installation and use of less

Documentation: https://cn.vitejs.dev/guide/features.html#css

  1. Install
yarn add less

Vite provides built-in support for .scss, .sass, .less, .styl and .stylus files, no need to install specific vite plugins for them, just install the preprocessor dependencies themselves and use them directly in the project.

  1. Test whether less works, and css module

In vue development, in order to prevent style pollution between components, it is usually necessary to set a locally effective style for the component.

  • In a .vue single file use:
<style scoped lang="less">
.header {
  font-size: 36px;
  font-weight: bold;
}
</style>
  • Use in .tsx files: Add .module (index.module.less) before the suffix of the style file, and import the style in tsx for use.
import classes from "./tsx.module.less"

const FcNode: FC<{ data: number }> = ({ data }) => {
  return (
    <>
      <hr />
      <div class={classes['son-header']}>子组件:
        {data < 10 ? <span>{data}</span> : <h1>{data}</h1>}
      </div>
    </>
  )
};

So far, the less syntax can be used normally in the project.

6. Unified introduction of styles

  • Create src/styles/reset.lessthe file, clearing the default styles.
  • Create src/styles/index.lessa file as a unified style management, and you can write some global styles at the same time.
@import "./reset.less";

/* Global css */
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  width: 100%;
  height: 100%;
}
  • main.tsIntroduced insrc/styles/index.less

7. Installation and use of ElementUI

Documentation: https://element-plus.org/zh-CN/

  1. Install
yarn add element-plus
  1. Introduce ElementUI as needed in the form of plug-ins
  • Create scr/plugins/element-plus.tsa plug-in, taking the introduction of the Button component as an example:
import {
    
     createApp } from "vue";
// 引入样式
import "element-plus/dist/index.css";
// 按需引入组件
import {
    
     ElButton, ElMessage } from "element-plus";

export default function loadComponent(app: ReturnType<typeof createApp>) {
    
    
  // 注册组件
  app.use(ElButton);
  app.config.globalProperties.$message = ElMessage;
}
  • Create scr/plugins/index.tsa file to facilitate the unified introduction of plug-ins:
import {
    
     createApp } from 'vue'
import elementPlugin from "./element-plus";

/**
 * @description 加载所有 Plugins
 * @param  {ReturnType<typeofcreateApp>} app 整个应用的实例
 */
export function loadAllPlugins(app: ReturnType<typeof createApp>) {
    
    
  elementPlugin(app)
}
  • src/main.tsLoad all plugins in a file :
import {
    
     createApp } from "vue";
import App from "./App.vue";
import {
    
     loadAllPlugins } from "./plugins";
import router from "./router";

// 应用实例
const app = createApp(App)

// 加载所有插件
loadAllPlugins(app)

app.use(router).mount("#app");
  • In the page use:
<template>
  <div class="header">
    <el-button>my button</el-button>
  </div>
</template>

8. vite configuration path alias

In order to facilitate code reuse, the custom configuration path alias is set to @, the specific configuration is as follows:

  • Configure in vite.config.tsthe file:
export default defineConfig({
    
    
  resolve: {
    
    
    alias: {
    
    
      "@": path.resolve(__dirname, "src"),
    },
  }
});
  • tsconfig.jsonconfigure in
"compilerOptions": {
    
    
    "paths": {
    
    
        "@/*": ["./src/*"]
    }
},
  • cite in the page
import TsxDemo from "@/components/TsxDemo"

(PS: Restart the next project after the configuration is complete)

9. i18n configuration multilingual

  1. Install vue-i18n
yarn add vue-i18n@next
  1. Create multilingual src/locale/zh-cn.tslanguage files, src/locale/ja.tslanguage files, and then create src/locale/indexfiles to import language files uniformly:
import Keys from "@/constant/key";
import {
    
     createI18n } from "vue-i18n";
import localeLangJa from "./ja";
import localeLangZhCn from "./zh-cn";

const messages = {
    
    
  "zh-cn": {
    
    
    ...localeLangZhCn,
  },
  ja: {
    
    
    ...localeLangJa,
  },
};

export const getLocale = () => {
    
    
  // 先寻找缓存里的lang
  const localLanguage = window.localStorage.getItem(Keys.languageKey);
  if (localLanguage) {
    
    
    return localLanguage;
  }
  // 如果缓存没有设置lang,根据所在地查询配置并显示对应lang
  const language = navigator.language.toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    
    
    if (language.indexOf(locale) > -1) {
    
    
      return locale;
    }
  }

  // 没有对应的语言配置,显示默认语言
  return "ja";
};

const i18n = createI18n({
    
    
  // 设置地区
  locale: getLocale(),
  // 设置地区信息
  messages,
});

export default i18n;
  1. Combined with ElementUI component library, configure multi-language

Inject the global multilingual configuration in the App.vue file:

<template>
  <el-config-provider :locale="locale">
    <router-view />
  </el-config-provider>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { getLocale } from "@/locale"

/** 配置默认语言 */
const locale = ref<string>(getLocale())
</script>
  1. Usage syntax: $t("key")

10. Design the Layout UI of the system

According to the requirements, a basic layout page Layout is required to facilitate the reuse of elements and some operations that need to be processed uniformly.

Guess you like

Origin blog.csdn.net/jexxx/article/details/128680853