Vue3——创建项目、添加依赖

2023-03-30  本文已影响0人  林几许

技术选择:vue3,vite,ts,less,pinia,axios,npm,node
前言:vue3开始推荐使用vite来构建项目,速度更快,而vue-cli维护了,ts来检查代码规范,css预编译推荐使用less,因为很多组件都是用less来写的,兼容性更好,pinia是作者尤雨溪推荐的新一代状态管理工具,更兼容v3+ts语法,后面大概率pinia会代替vuex的,pinia的写法更为简化。

1.vite创建Vue3项目

创建命令:

npm create vite@latest

填写项目名:

Project name: >> vite-vue3-ts-demo

选择vue:

√ Project name: ... vite-vue3-ts-demo
? Select a framework: » - Use arrow-keys. Return to submit.
    Vanilla
>   Vue
    React
    Preact
    Lit
    Svelte
    Others

选择ts:

? Select a variant: » - Use arrow-keys. Return to submit.
    JavaScript
>   TypeScript
    Customize with create-vue 
    Nuxt 

创建完成,可以根据地址直接找到目标项目,丢到vscode中,然后安装依赖:

Scaffolding project in C:\Users\Administrator\vite-vue3-ts-demo...
Done. Now run:
  cd vite-vue3-ts-demo
  npm install
  npm run dev

2.安装依赖,配合路由和一些基础配置

先安装2个插件volar


插件下载

配置@别名

npm i @types/node
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from "path"

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve:{
    alias:{
      "@": resolve(__dirname,"./src")
    }
  }
})

tsconfig.json添加配置

{
  "compilerOptions": {
    "target": "ESNext",
    ···
    // 配置@别名
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
  },
}

安装less

 npm i -d less

安装 vue-router

npm i vue-router@4

main.ts文件引入router(此时发现@后面没有提示,需要加个插件Path-intellisense,并配置)


步骤1
步骤2

配置如下

{
    //添加以下配置(主要是前两个)
    "path-intellisense.mappings": {
        "@/": "${workspaceFolder}/src",
        "/": "${workspaceFolder}",
        "lib": "${workspaceFolder}/lib",
        "global": "/Users/dummy/globalLibs"
    },
    "path-intellisense.autoTriggerNextSuggestion": true
}

提示就出来了


不需输入首字母提示成功显示

在src下创建一个 routes 文件夹,再创建一个 index.ts 文件

import {createRouter,createWebHistory} from "vue-router"

let routes = [
    {
        path:"/",
        name:"home",
        component:() => import("@/pages/home.vue")
    }
]

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

export default router

main.ts引入成功

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from '@/routes/index'

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

修改App.vue文件(Vue3/Vue Router4下使用Keep-alive)

<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="includeList">
      <component :is="Component"></component>
    </keep-alive>
  </router-view>

</template>
 
<script lang="ts">
//使用动态include解析
  export default {
    name: 'App',
    data(){
      return {
        includeList : []
      }
    },
    watch:{
      $route(to:any) {
        //监听路由变化,把配置路由中keepAlive为true的name添加到include动态数组中
        const that:any = this;
        if(to.meta.keepAlive && that.includeList.indexOf(to.name) === -1){
          that.includeList.push(to.name);
        }
      }
    }
  }
</script>

运行项目,正常显示

npm run dev
上一篇 下一篇

猜你喜欢

热点阅读