vue3初始化项目

Vue3 + Ts + Pinia + Vue-Router + Axios + Tailwindcss 初始化项目

1. 创建项目

yarn create vite

选择Vue3 + Ts

配置别名

  1. vue等文件别名
// vite.config.ts
import path from 'path'
export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
})
  1. ts文件别名
//  tsconfig.json
{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "@/*": [
                "src/*"
            ]
        }
    }
}

2. 安装Pinia

yarn add pinia

3.安装Vue-Router

yarn add vue-router@4
  1. 封装vue-router

  2. ```typescript
    import { createRouter, createWebHashHistory } from ‘vue-router’
    import layoutVue from ‘@/layout/layout.vue’

    let HomeRoutr = {
    path: ‘/‘,
    name: ‘main’,
    mate: {

    title: '首页',
    KeepAlive: true,
    

    },
    component: () => import(‘@/views/main/main.vue’),
    }
    const routes = [
    {

    path: '/',
    component: layoutVue,
    children: [HomeRoutr],
    

    },
    {

    path: '/login',
    name: 'login',
    mate: {
      title: '登录',
      KeepAlive: true,
    },
    component: () => import('@/views/login/login.vue'),
    

    },
    ]

    export default createRouter({
    routes: routes,
    history: createWebHashHistory(),
    })

    
    3. 路由守卫
    
       ```typescript
       // 路由前置守卫
       const beforeEach = (to: any, from: any, next: any) => {
         // 判断是否登录
         if (to.name !== 'login' && !useStorage.getStorage('token')) {
           console.log('to', to)
           MessagePlugin.error('用户未登录, 或者登录已过期')
           next('/login')
         }else{
           next()
         }
       }
       
       const router = createRouter({
         history: createWebHistory(),
         routes,
       })
       
       router.beforeEach(beforeEach)
  3. main.ts中useRouter

    const app = createApp(App)
    app.use(router)
    app.mount('#app')

4. 安装Axios

yarn add axios
  1. 封装axios

     //http.ts
     import axios from 'axios'
     import { MessageInfoOptions, MessagePlugin } from 'tdesign-vue-next'
     
     export const axiosInstance = axios.create({
       baseURL: '/api',
       timeout: 5000,
       headers: {
         'Content-Type': 'application/json;charset=UTF-8',
       },
     })
     
     axiosInstance.interceptors.request.use((config) => {
       return config
     }),
       (error: any) => {
         return Promise.reject(error)
       }
     
     axiosInstance.interceptors.response.use((response) => {
         // 判断请求状态码是否为200
         if (response.status !== 200) {
             let msg:(MessageInfoOptions|string) = {
                 placement:'top',
                 duration:3000,
                 content:response.data.msg || '请求失败',
             }
             MessagePlugin.error(msg)
         }
       return response
     }),
       (error: any) => {
         return Promise.reject(error)
       }
     
     export default axiosInstance
    
    2. 配置代理
    
       ```typescript
       export default defineConfig({
         server: {
           host: '0.0.0.0', //允许本机
           proxy: {
             '/api': {
               target: 'http://localhost:3000/api/v1',
               changeOrigin: true,
               rewrite: (path) => path.replace(/^\/api/, ''),
             },
           },
         },
       })
  2. 封装api请求

    //  api/index.ts
    import user from './user'
    
    const api = {
        user
    }
    export default api;
    //  api/user.ts
    import http from './http'
    import { LoginData } from '@/types/user'
    
    const Login = (data: LoginData) => {
        return http.post('/login', data)
    }
    
    const user = {
        Login
    }
    export default user
    //  type/user.ts
    
    type LoginData = {
        username: string
        password: string
    }
    
    export type {
        LoginData
    }
  3. 使用请求

    这里引用type的时候使用@符号会报错是因为需要在tsconfig.json配置@

    import { LoginData } from '@/types/user';
    
    const formData = reactive<LoginData>({
      username: '',
      password: '',
    })
    
    api.user.Login(formData).then(res => {
      console.log(res)
    })

5. 安装TailwindCss

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p

在生成的tailwind.config.js添加purge

module.exports = {
  purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
  content: [],
  theme: {
    extend: {},
  },
  plugins: [],
}

在全局引入的css文件中添加

/* ./src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;