Vue3.x全家桶+vite+TS-搭建Vue3.x项目
一、搭建基础项目
1、vite创建项目
使用 vite 搭建项目
npm init @vitejs/app
or
yarn create @vitejs/app
根据步骤选择:
- 项目名称
- 框架(vue,react…)
- js或ts
3、运行项目
cd 项目目录
npm install
npm run dev
2、环境变量设置介绍
vite serve 时是development开发模式, vite build时是production生产模式。
分别创建配置文件: .env.development 、.env.production
注意: 命名规范 VITE_为前缀的变量才会暴露给经过vite处理的代码
.env.development
# .env.development
VITE_APP_TITLE = MY PROJECT
.env.production
# .env.production
NODE_ENV = development
#base api
VITE_APP_BASE_API = 'http://vitetest.com'
读取环境变量
读取环境变量使用import.meta.env.xxx,可在 main.js中测试
// base api
console.log(import.meta.env.VITE_APP_BASE_API);
// title
console.log(import.meta.env.VITE_APP_TITLE);
vite配置多环境打包
- 安装cross-env
- cross-env 通过js在平台设置不同的环境变量的工具
npm install --save-dev cross-env
- 配置环境
在项目打包的时候,我们通常需要根据环境变量来区分不同的环境,以请求不同的后台接口
那么我们在项目的根目录下创建如下的环境配置文件,以production为例,在项目根目录下创建.env.production,并新增环境变量VITE_PROJECT_ENV = 'production',需要注意的是,环境变量必须以VITE开头
# .env.production
NODE_ENV = development
#base api
VITE_APP_BASE_API = 'http://vitetest.com'
#环境变量
VITE_PROJECT_ENV = 'production'
- 配置打包
修改package.json (根据自己的实际情况增减)
"scripts": {
"serve": "cross-env vite --mode development",
"product": "cross-env vite --mode production",
"build": "cross-env vite build --mode development",
"build:product": "cross-env vite build --mode production"
}
二、配置Router
1、安装路由
这里要注意我们安装的要是4以上的所有采用@next进行安装
npm i vue-router@next -S
2、配置路由
在 src 下新建 router 文件夹,并在文件夹内创建 index.ts
vue-router 参数
- 创建router实例:createRouter
- router的模式分为:
- createWebHistory -- history模式
- createWebHashHistory -- hash模式 - routes的约束类型是:RouteRecordRaw
import { createRouter, createWebHashHistory } from 'vue-router';
import Home from '../views/Home.vue';
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
});
export default router
扩展路由额外属性
在实际项目开发中,常常会遇到这么一个场景,某一个路由是不需要渲染到侧边栏导航上的,此时我们可以给该路由添加一个hidden属性来实现。
在ts的强类型约束下,添加额外属性就会报错,那么我们就需要扩展RouteRecordRaw类型。
// 联合类型
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
type RouteConfig = RouteRecordRaw & {hidden?: boolean}; //hidden 是可选属性
import Home from '../views/Home.vue';
const routes: Array< RouteRecordRaw > = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
3、引入
我们在main.ts文件中引入Vue-Router,如下所示。
import router from './router';
createApp(App).use(router).mount("#app");
最后和vue2一样在App.vue中写入挂在渲染的组件
<router-view/>
三、配置Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
1、安装vuex
使用Vuex之前,需要先安装Vuex插件,如下所示。
npm install vuex@next --save
2、配置vuex
安装完成之后,需要先初始化Vuex。首先,创建一个store/index.ts文件,添加如下代码
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
封装一下
不同模块执行不同的业务逻辑。
以用户模块为例
- 新建user.ts
import REQUEST_DATA from "@/api/requestHandler";
const state = {
userInfo:[]
};
const mutations = {
setStateItem(state:any, data:any) {
state[data.key] = data.value;
}
};
const actions = {
async getUserData({ commit }:any, data?:any):Promise<any> {
try {
const res = await REQUEST_DATA('userInfoUri', data);
if (res.data.code == 200) {
commit("setStateItem", {
key: "reasonList",
value: res.data.data
});
data.cb && data.cb(res.data.data.satisfaction_status)
} else {
//给出错误提示toast
return false;
}
} catch (e) {
return false;
}
},
};
export default {
state,
actions,
mutations,
namespaced: true
};
- index.ts中调用
import { createStore } from 'vuex'
import user from './modules/user'
const store = createStore({
modules: {
user,
},
})
export default store
3、引入
我们在main.ts文件中引入Vuex,如下所示。
import { createApp } from 'vue'
import App from './App.vue'
import router from './router';
import store from './store'
createApp(App).use(store).use(router).mount("#app");
4、页面调用
- import { useStore } from 'vuex';
- const store = useStore();
- store中的方法:
| 方法 | 介绍 |
|---|---|
| store.state.xxx | 访问 state |
| store.getters.xxx | 访问 getter |
| store.xxx | 访问 Store 的函数 |
| store.commit("xxx", payload?) | 调用 (优化约束,以强化提示) |
| store.commits.xxx(payload?) | 调用 commit |
| store.dispatch("xxx", payload?) | 调用 (优化约束,以强化提示) |
| store.dispatchs.xxx(payload?) | 调用 dispatch |
| store.subscribe(fn) | 优化约束,以强化提示 |
| store.subscribeAction(fn) | 优化约束,以强化提示 |
| store.mapState({...}) | 映射 state |
| store.mapStateOfKeys(...) | 映射 state |
| store.mapGetters({...}) | 映射 getters |
| store.mapGettersOfKeys(...) | 映射 getters |
| store.mapActions({...}) | 映射 actions |
| store.mapActionsOfKeys(...) | 映射 actions |
| store.mapMutations({...}) | 映射 mutations |
| store.mapMutationsOfKeys(...) | 映射 mutations |
<template>
<h1>Home Page</h1>
<h2>{{count}}</h2>
<button @click="handleClick">click</button>
</template>
<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useStore } from 'vuex';
export default defineComponent({
setup () {
const store = useStore();
const count = computed(() => store.state.home.count);
const handleClick = () => {
store.commit('user/add');
};
return {
handleClick,
count
};
}
})
</script>
四、alias起别名
- vite.config.ts
在过去使用vue-cli的时候,我们总是使用@去引入某些文件,由于Vite没有提供类似的配置,所以我们需要手动的对其进行相关配置,才能继续使用@符号去快捷的引入文件。首先,我们需要修改vite.config.ts的配置。
核心代码
resolve: {
alias: [
{
find: '@',
replacement: '/src',
},
{ find: 'views', replacement: '/src/views' },
{ find: 'components', replacement: '/src/components' },
]
}
完成代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve:{
alias:[
{
find:'@',
replacement:'/src'
},
{
find:'views',
replacement:'/src/views'
},
{
find:'components',
replacement:'/src/components'
},
]
}
})
- tsconfig.json
然后,我们在修改tsconfig.json文件
核心代码
"types": ["vite/client", "jest"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
完成代码
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": [
"esnext",
"dom"
],
"types": ["vite/client", "jest"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue"
]
}
五、基础语法
1、定义data
- script标签上:lang="ts"
- 定义一个类型type或者接口:interface来约束data
- 定义响应式数据:可以使用ref或者toRefs来
- 使用ref在setup读取的时候需要获取xxx.value,但在template中不需要
- 使用reactive时,可以用toRefs解构导出,在template就可以直接使用了
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
type Todo = {
id: number;
name: string;
completed: boolean;
};
export default defineComponent({
setup() {
const data = reactive({
todoList: [] as Todo[],
});
const count = ref(0);
console.log(count.value);
return {
...toRefs(data),
};
},
});
</script>
2、定义props
props需要使用PropType泛型来约束
<script lang="ts">
import { defineComponent, PropType } from "vue";
interface UserInfo {
id: number;
name: string;
age: number;
}
export default defineComponent({
props: {
userInfo: {
type: Object as PropType<UserInfo>, // 泛型类型
required: true,
},
},
});
</script>
3、定义methods
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
type Todo = {
id: number;
name: string;
completed: boolean;
};
export default defineComponent({
setup() {
const data = reactive({
todoList: [] as Todo[],
});
// 约束输入和输出类型
const newTodo = (name: string): Todo => {
return {
id: 1,
name,
completed: false,
};
};
const addTodo = (todo: Todo): void => {
data.todoList.push(todo);
};
return {
...toRefs(data),
newTodo,
addTodo,
};
},
});
</script>
Vue3.x全家桶+vite+TS-搭建Vue3.x项目的更多相关文章
- Vue3.x全家桶+vite+TS-构建Vue3基本框架
目录 一.搭建基础项目 1.vite创建项目 3.运行项目 2.环境变量设置介绍 vite配置多环境打包 二.配置Router 1.安装路由 2.配置路由 3.引入 三.配置Vuex 1.安装vuex ...
- react全家桶从0搭建一个完整的react项目(react-router4、redux、redux-saga)
react全家桶从0到1(最新) 本文从零开始,逐步讲解如何用react全家桶搭建一个完整的react项目.文中针对react.webpack.babel.react-route.redux.redu ...
- React全家桶打造共享单车后台管理系统项目_第1篇_项目环境搭建_首页编写
1.项目介绍 项目github地址:https://github.com/replaceroot/React-manageSystem 项目整体架构: 课程大纲: 第一章:React基础知识 ...
- 从0搭建vue3组件库:Shake抖动组件
先看下效果 其实就是个抖动效果组件,实现起来也非常简单.之所以做这样一个组件是为了后面写Form表单的时候会用到它做一个规则校验,比如下面一个简单的登录页面,当点击登录会提示用户哪个信息没输入,当然这 ...
- 从0搭建vue3组件库: Input组件
本篇文章将为我们的组件库添加一个新成员:Input组件.其中Input组件要实现的功能有: 基础用法 禁用状态 尺寸大小 输入长度 可清空 密码框 带Icon的输入框 文本域 自适应文本高度的文本域 ...
- vue+ts搭建项目
Tip: 为了避免浪费您的时间,本文符合满足以下条件的同学借鉴参考 1.本文模版不适用于小型项目,两三个页面的也没必要用vue2.对typescript.vue全家桶能够掌握和运用 此次项目模版主要涉 ...
- 手把手教你全家桶之React(一)
前言 最近项目用到react,其实前年我就开始接触react,时光匆匆,一直没有时间整理下来(太懒啦)!如今再次用到,称工作间隙,对全家桶做一次总结,项目源码地址.废话不多说,上码. 创建一个文件目录 ...
- 基于 vite 创建 vue3 全家桶项目(vite + vue3 + tsx + pinia)
vite 最近非常火,它是 vue 作者尤大神发布前端构建工具,底层基于 Rollup,无论是启动速度还是热加载速度都非常快.vite 随 vue3 正式版一起发布,刚开始的时候与 vue 绑定在一起 ...
- vue3 vite2 封装 SVG 图标组件 - 基于 vite 创建 vue3 全家桶项目续篇
在<基于 vite 创建 vue3 全家桶>一文整合了 Element Plus,并将 Element Plus 中提供的图标进行全局注册,这样可以很方便的延续 Element UI 的风 ...
随机推荐
- 线程休眠_sleep
线程休眠_sleep sleep(时间)指定当前线程阻塞的毫秒数: sleep存在异常InterruptedException: sleep时间到达后线程进入就绪状态: sleep可以模拟网络延时,倒 ...
- connect()函数阻塞问题
方法一:采用select 在学习嵌入式Linux网络编程中,很多同学都发现了一个问题,那就是调用connect函数时,如果服务端关闭,客户 端调用connect()函数时,发现阻塞在那里,而且利用ct ...
- Linux进程间通信方式--信号,管道,消息队列,信号量,共享内存
1.概述 通信方法 无法介于内核态与用户态的原因 管道(不包括命名管道) 局限于父子进程间的通信. 消息队列 在硬.软中断中无法无阻塞地接收数据. 信号量 无法介于内核态和用户态使用. 内存共享 需要 ...
- Spring学习04(使用注解开发)
7.使用注解开发 说明:在spring4之后,想要使用注解形式,必须得要引入aop的包. 在配置文件当中,还得要引入一个context约束 <?xml version="1.0&quo ...
- Solon 1.5.24 发布
本次版本主要变化: 修复 solon.extend.sessionstate.jwt 在特定场景下会无限次解析的问题 优化 solon.extend.cors 对头信息的处理 插件 solon.boo ...
- Golang语言系列-17-Gin框架
Gin框架 Gin框架简介 package main import ( "github.com/gin-gonic/gin" "io" "net/ht ...
- Java 多线程与并发【原理第二部分笔记】
Java 多线程与并发[原理第二部分笔记] 什么是Java内存模型中的happens-before Java内存模型,即JMM,本身是一种抽象的概念,并不是真实存在的,他描述的是一组规则或者说是一种规 ...
- docker搭建clickhouse集群
//需要先搭建zookeeper集群.机器1: sudo docker run -d \ --name clickhouse --ulimit nofile=262144:262144 \ -p 81 ...
- 基于 CODING CD + Nocalhost 在大型应用的 ChatOps 实践
本文作者:红亚科技 CTO--卢兴民 红亚科技聚焦信息技术发展,为信息技术相关专业提供优质教学服务 背景 ChatOps 最早起源于 GitHub,它以沟通平台为中心,通过与机器人产生对话和交互,使开 ...
- 对Web(Springboot + Vue)实现文件下载功能的改进
此为 软件开发与创新 课程的作业 对已有项目(非本人)阅读分析 找出软件尚存缺陷 改进其软件做二次开发 整理成一份博客 原项目简介 本篇博客所分析的项目来自于 ジ绯色月下ぎ--vue+axios+sp ...