vue3+TS项目开发步骤

570 阅读4分钟

插件json to ts

全选json文件里的内容 使用方法 ctrl + shift + alt + s

vite安装项目

npm create vite@latest

src别名

找到 vite.config.ts 文件

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// 引入node提供的内置模块path:可以获取绝对路径
import path from "path"

export default defineConfig({
  plugins: [vue()],
  
  // src文件夹配置别名
  resolve:{
    alias:{
      "@":path.resolve(__dirname,'src')
    }
  }
})


如果提示找不到模块“path”或其相应的类型声明

安装@typss/node这是TS的一个声明文件包,用于描述Node.js核心模块和常用的第三方库的类型信息

npm i @types/node

找到tsconfig.json 配置文件,找到compilerOptions配置项,添加以下配置。 这一步是让IDE可以对路径进行智能提示

  "baseUrl": ".",
    "paths": {
      "@/*":["src/*"]
    }

安装SASS

npm i sass

去除默认样式

reset.scss 去这个网址reset.scss复制下来即可

/**
 * ENGINE
 * v0.2 | 20150615
 * License: none (public domain)
 */

 *,
 *:after,
 *:before {
     box-sizing: border-box;
 
     outline: none;
 }
 
 html,
 body,
 div,
 span,
 applet,
 object,
 iframe,
 h1,
 h2,
 h3,
 h4,
 h5,
 h6,
 p,
 blockquote,
 pre,
 a,
 abbr,
 acronym,
 address,
 big,
 cite,
 code,
 del,
 dfn,
 em,
 img,
 ins,
 kbd,
 q,
 s,
 samp,
 small,
 strike,
 strong,
 sub,
 sup,
 tt,
 var,
 b,
 u,
 i,
 center,
 dl,
 dt,
 dd,
 ol,
 ul,
 li,
 fieldset,
 form,
 label,
 legend,
 table,
 caption,
 tbody,
 tfoot,
 thead,
 tr,
 th,
 td,
 article,
 aside,
 canvas,
 details,
 embed,
 figure,
 figcaption,
 footer,
 header,
 hgroup,
 menu,
 nav,
 output,
 ruby,
 section,
 summary,
 time,
 mark,
 audio,
 video {
     font: inherit;
     font-size: 100%;
 
     margin: 0;
     padding: 0;
 
     vertical-align: baseline;
 
     border: 0;
 }
 
 article,
 aside,
 details,
 figcaption,
 figure,
 footer,
 header,
 hgroup,
 menu,
 nav,
 section {
     display: block;
 }
 
 body {
     line-height: 1;
 }
 
 ol,
 ul {
     list-style: none;
 }
 
 blockquote,
 q {
     quotes: none;
     &:before,
     &:after {
         content: '';
         content: none;
     }
 }
 
 sub,
 sup {
     font-size: 75%;
     line-height: 0;
 
     position: relative;
 
     vertical-align: baseline;
 }
 sup {
     top: -.5em;
 }
 sub {
     bottom: -.25em;
 }
 
 table {
     border-spacing: 0;
     border-collapse: collapse;
 }
 
 input,
 textarea,
 button {
     font-family: inhert;
     font-size: inherit;
 
     color: inherit;
 }
 
 select {
     text-indent: .01px;
     text-overflow: '';
 
     border: 0;
     border-radius: 0;
 
     -webkit-appearance: none;
        -moz-appearance: none;
 }
 select::-ms-expand {
     display: none;
 }
 
 code,
 pre {
     font-family: monospace, monospace;
     font-size: 1em;
 }

路由

npm install vue-router

  1. 在src目录下创建 router -> index.ts 代码如下:
import { createRouter,createWebHistory } from "vue-router";
import Home from "@/views/home/index.vue"
import Welcome from '@/views/index/components/welcome.vue'
const routes = [
  {
    path:'/home',
    component:Home
  },
  {
    path:'/hopital',
    component:() => import('@/views/hopital/index.vue'),
    redirect:'/welcome',
    children:[
      {path:'/welcome',component:Welcome}
    ]
  },
  {
    path:'/',
    redirect:'/home'
  }
]
export default createRouter({
  history:createWebHistory(),
  routes,
  // 滚动行为:控制滚动条的位置
  scrollBehavior(){
    return {
      left: 0,
      top: 0
    }
  }
})
  1. main.ts中导入,代码如下:
import router from '@/router'
app.use(router)
  1. src目录下创建views,作为存放路由页面
  2. 在需要路由的位置设置<RouterView></RouterView>

Pinia

npm i pinia

  1. 在main.js中
import {createPinia} from 'pinia'
const pinia = createPinia()
app.use(pinia)
  1. 在src目录下创建store->文件名.js 例:
import { defineStore } from 'pinia'
import {ref} from 'vue'
export const playStore = defineStore('play', () => {
  const song = ref({})
  const isPlay = ref(false)

  return { isPlay,song }
})
  1. 使用: 在要使用的地方引入 例:
// pinia
import {playStore} from '../store/play'
const play = playStore()
console.log(play.isPlay);

axios

安装 npm i axios

二次封装

二次封装的目的: 利用axios的请求、响应拦截器

  1. 在src目录下创建utils->request.ts
  2. request.ts 里面的代码
// 1.导入axion
import axios from "axios";
const request =  axios.create({
  // 2.设置基础路径
  baseURL:'',
  // 3.超时时间
  timeout:5000
})
// 4.请求拦截器
request.interceptors.request.use((config)=>{
  // config:请求拦截器回调注入的对象(配置对象),配置对象的身上最重要的是有headers属性
  // 通过headers携带公共的参数 如:token
  return config;
})
// 5.响应拦截器
request.interceptors.response.use((response)=>{
  // 响应拦截器成功的回调,一般会进行简化数据
  return response;
},(error)=>{
  //  处理返回的错误
  return Promise.reject(new Error(error.message))
})

// 6.对外暴露,方便调用
export default request;
  1. 代理跨域

在vite.config.ts中与plugins同级配置,以下为简单配置

server:{
    proxy:{
      '/api': {
        // 请求的地址
        target: '',
        changeOrigin: true,
        // 路径重写,根据实际需要来决定需不需要将 /api 替换成空
        rewrite: (path) => path.replace(/^\/api/, ''),
      }
    }
  }

4.在src目录下创建 api文件夹,里面的文件用来统一管理网络请求,使用时调用即可 如下:

import request  from "@/utils/request.ts"

// 使用枚举类型统一管理api方便查找
enum API{
  HOSPITAL_URL='地址'
}

export function getHome(page:number,limit:number){
  return request({
    url:API.HOSPITAL_URL,
    method:"get",
    params:{
      page,
      limit
    }
  })
}

设置请求头的内容

如:携带token

  1. 首先获取本地存储(或者pinia里)的token
  2. 在请求拦截器中加入以下内容:
if(获取的token){
    config.headers.token = 获取的token
}

Element Plus

scss使用:deep()

最好外面包一层,这样权重才够

.search{
  :deep(.el-input__wrapper){
    width: 600px;
    margin-right: 10px;
  }
}

TS

类型怎么设置

  1. 可以在src目录下专门创建一个文件夹来存放(随意,根据自身习惯)
  2. 我的方法一般是
// 1.首先先定义一个接口返回的数据类型
export interface ResponseData {
  code: Number,
  message: String,
  ok: Boolean,
}
// 2.根据每个接口返回的data不同,在继承第一步后定义data的类型
export interface name extends ResponseData{
  data:dataType
}
// 3.dataType就实际情况实际应用
export interface dataType {
  id:String,
  ......
}
// 1.定义对象类型
export interface name {
 param: {
    name: String,
    address: String
  },
}
// 2.定义数组类型
export interface name {
 param: String[],
}

忽略TS的校验

// @ts-ignore

注释符不能少,写在报错行的上面

TS报错

VSCode 中,TS 提示 ”无法找到 *.vue 声明文件“ 的解决方案

在src目录下创建 “xxx.d.ts” 文件

// 以下两种方案二选一

// 方案一
declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

// 方案二
declare module '*.vue' {
  import { defineComponent } from 'vue'
  const Component: ReturnType<typeof defineComponent>
  export default Component
}

eslint

格式化工具和ESlint产生了冲突

  1. 在最外层目录创建文件 .prettierrc
  2. 内容如下
{
    "semi":false, // 去掉分号
    "singleQuote":true // 启动单引号
    
}