vite + ts 快速搭建 vue3 项目 以及介绍相关特性
博客地址:https://ainyi.com/98
Vue3.0,One Piece
接下来得抽空好好学习了
vite
尤大在 Vue 3.0 beta 直播中推荐了 vite 的工具,强调:针对Vue单页面组件的无打包开发服务器,可以直接在浏览器运行请求的 vue 文件
很新颖,这篇博客用它来搭建一个 vue3 的项目试试
Vite 是面向现代浏览器,基于原生模块系统 ESModule 实现了按需编译的 Web 开发构建工具。在生产环境下基于 Rollup 打包
- 快速冷启动服务器
- 即时热模块更换(HMR)
- 真正的按需编译
node >= 10.16.0
搭建
使用 vite 搭建项目
npm init vite-app <project-name>
安装 typescript、vue-router@next、axios、eslint-plugin-vue、sass 等相关插件
配置
vite.config.ts
vite.config.ts 相当于 @vue-cli 项目中的 vue.config.js
我这简单配置一下:
import path from 'path'
module.exports = {
alias: {
'/@/': path.resolve(__dirname, './src')
},
optimizeDeps: {
include: ['lodash']
},
proxy: {}
}
Router
在 src 下新建 router 文件夹,并在文件夹内创建 index.ts
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('/@/views/Home.vue')
},
{
path: '/lifeCycle',
name: 'lifeCycle',
component: () => import('/@/views/LifeCycle.vue')
}
]
export default createRouter({
history: createWebHistory('/krry/'),
routes
})
ts types
项目根目录下新建 tsconfig.json 写入相关配置
{
"compilerOptions": {
...// 其他配置
"paths": {
"/@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/types/images.d.ts",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
src 目录下新建 types 文件夹,里面需要配置 ts 的类型
shims-vue.d.ts
declare module '*.vue' {}
images.d.ts
declare module '*.svg'
declare module '*.png'
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.gif'
declare module '*.bmp'
declare module '*.tiff'
main.ts
import { createApp } from 'vue'
import router from '/@/router'
import App from '/@/App.vue'
const app = createApp(App)
app.use(router)
app.mount('#app')
然后就可以快乐地写代码了
vue3 知识
setup
vue3 中用 setup 函数整合了所有的 api;只执行一次,在生命周期函数前执行,所以在 setup 函数中拿不到当前实例 this,不能用 this 来调用 vue2 写法中定义的方法
它将接受两个参数:props、context
// props - 组件接受到的属性 context - 上下文
setup(props, context) {
return {
// 要绑定的数据和方法
}
}
props
setup 函数中的 props 是响应式的,当传入新的 prop 时,它将被更新
但是,因为 props 是响应式的,不能使用 ES6 解构,因为它会消除 prop 的响应性
如果需要解构 prop,可以通过使用 setup 函数中的 toRefs 来安全地完成此操作
import { toRefs } from 'vue'
setup(props) {
const { title } = toRefs(props)
console.log(title.value)
}
context
context 暴露三个组件的 property:{ attrs, slots, emit }
它是一个普通的 JavaScript 对象,不是响应式的,这意味着你可以安全地对 context 使用 ES6 解构
生命周期
通过在生命周期钩子前面加上 “on” 来访问组件的生命周期钩子
因为 setup 是围绕 beforeCreate 和 created 生命周期钩子运行的,所以不需要显式地定义它们
换句话说,在这两个钩子中编写的任何代码都应该直接在 setup 函数中编写
setup() {
onMounted(() => {
console.log('组件挂载')
})
onUnmounted(() => {
console.log('组件卸载')
})
onUpdated(() => {
console.log('组件更新')
})
onBeforeUpdate(() => {
console.log('组件将要更新')
})
onActivated(() => {
console.log('keepAlive 组件 激活')
})
onDeactivated(() => {
console.log('keepAlive 组件 非激活')
})
return {}
}
ref、reactive
ref 可以将某个普通值包装成响应式数据,仅限于简单值,内部是将值包装成对象,再通过 defineProperty 来处理的
通过 ref 包装的值,取值和设置值的时候,需用通过 .value来进行设置
可以用 ref 来获取组件的引用,替代 this.$refs 的写法
reactive 对复杂数据进行响应式处理,它的返回值是一个 proxy 对象,在 setup 函数中返回时,可以用 toRefs 对 proxy 对象进行结构,方便在 template 中使用
使用如下:
<template>
<div>
<div>
<ul v-for="ele in eleList" :key="ele.id">
<li>{{ ele.name }}</li>
</ul>
<button @click="addEle">添加</button>
</div>
<div>
<ul v-for="ele in todoList" :key="ele.id">
<li>{{ ele.name }}</li>
</ul>
<button @click="addTodo">添加</button>
</div>
</div>
</template>
<script>
import { ref, reactive, toRefs } from 'vue'
export default {
setup() {
// ref
const eleList = ref([])
function addEle() {
let len = eleList.value.length
eleList.value.push({
id: len,
name: 'ref 自增' + len
})
}
// reactive
const dataObj = reactive({
todoList: []
})
function addTodo() {
let len = dataObj.todoList.length
dataObj.todoList.push({
id: len,
name: 'reactive 自增' + len
})
}
return {
eleList,
addEle,
addTodo,
...toRefs(dataObj)
}
}
}
</script>
computed、watch
// computed
let sum = computed(() => dataObj.todoList.length + eleList.value.length)
console.log('setup引用computed要.value:' + sum.value)
// watch
watch(
eleList,
(curVal, oldVal) => {
console.log('监听器:', curVal, oldVal)
},
{
deep: true
}
)
watchEffect
响应式地跟踪函数中引用的响应式数据,当响应式数据改变时,会重新执行函数
const count = ref(0)
// 当 count 的值被修改时,会执行回调
const stop = watchEffect(() => console.log(count.value))
// 停止监听
stop()
还可以停止监听,watchEffect 返回一个函数,执行后可以停止监听
与 vue2 一样:
const unwatch = this.$watch('say', curVal => {})
// 停止监听
unwatch()
useRoute、useRouter
import {useRoute, useRouter} from 'vue-router'
const route = useRoute() // 相当于 vue2 中的 this.$route
const router = useRouter() // 相当于 vue2 中的 this.$router
route 用于获取当前路由数据
router 用于路由跳转
vuex
使用 useStore 来获取 store 对象 从 vuex 中取值时,要注意必须使用 computed 进行包装,这样 vuex 中状态修改后才能在页面中响应
import {useStore} from 'vuex'
setup(){
const store = useStore() // 相当于 vue2 中的 this.$store
store.dispatch() // 通过 store 对象来 dispatch 派发异步任务
store.commit() // commit 修改 store 数据
let category = computed(() => store.state.home.currentCagegory
return { category }
}
博客地址:https://ainyi.com/98
vite + ts 快速搭建 vue3 项目 以及介绍相关特性的更多相关文章
- 使用IDEA快速搭建Springboot项目
Spring Boot是由Pivotal团队提供的全新框架,设计目的是用来简化新Spring应用的初始搭建以及开发过程.它主要推崇的是'消灭配置’,实现零配置. 下面就介绍一下如何使用idea快速搭建 ...
- Spring Boot入门-快速搭建web项目
Spring Boot 概述: Spring Boot makes it easy to create stand-alone, production-grade Spring based Appli ...
- 快速搭建Vue项目
快速搭建Vue项目 第一次安装vue项目Vue推荐开发环境Node.js 6.2.0.npm 3.8.9.webpack 1.13.vue-cli 2.5.1.webstrom2016 安装环境: 安 ...
- 在线官网Spring Initializr 或 IntelliJ IDEA 快速搭建springboot项目
Spring Boot是由Pivotal团队提供的全新框架,设计目的是用来简化新Spring应用的初始搭建以及开发过程.它主要推崇的是'消灭配置’,实现零配置. 那么,如何快速新建一个一个spring ...
- (05节)快速搭建SSM项目
1.1 快速搭建Web项目 注意点:name:archetypeCatalog,value:internal 原因:Intellij IDEA根据maven archetype的本质,执行mvn a ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_2-2.快速搭建SpringBoot项目,采用IDEA
笔记 2.快速搭建SpringBoot项目,采用IDEA 简介:使用SpringBoot start在线生成项目基本框架并导入到IDEA中 参考资料: IDEA使用文档 ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_2-1.快速搭建SpringBoot项目,采用Eclipse
笔记 1.快速搭建SpringBoot项目,采用Eclipse 简介:使用SpringBoot start在线生成项目基本框架并导入到eclipse中 1.站点地址:http://start. ...
- 利用vue-cli3快速搭建vue项目详细过程
一.介绍 Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统.有三个组件: CLI:@vue/cli 全局安装的 npm 包,提供了终端里的vue命令(如:vue create .vue ...
- Spring-Boot快速搭建web项目详细总结
最近在学习Spring Boot 相关的技术,刚接触就有种相见恨晚的感觉,因为用spring boot进行项目的搭建是在太方便了,我们往往只需要很简单的几步,便可完成一个spring MVC项目的搭建 ...
随机推荐
- ECharts系列:玩转ECharts之常用图(折线、柱状、饼状、散点、关系、树)
一.背景 最近产品叫我做一些集团系列的统计图,包括集团组织.协作.销售.采购等方面的.作为一名后端程序员,于是趁此机会来研究研究这个库. 如果你仅仅停留在用的层面,那还是蛮简单的. 二.介绍 ECha ...
- IDEA文本编辑区的护眼绿豆沙色配置
第一步:打开IDEA -> File -> settings -> Editor -> Color Scheme -> General 第二步:找到右方Text -> ...
- python单元测试框架pytest
首先祝大家国庆节日快乐,这个假期因为我老婆要考注会,我也跟着天天去图书馆学了几天,学习的感觉还是非常不错的,这是一篇总结. 这篇博客准备讲解一下pytest测试框架,这个框架是当前最流行的python ...
- Thymeleaf 异常:Exception processing template "index": An error happened during template parsing (template: "class path resource [templates/index.html]")
Spring Boot 项目,在 Spring Tool Suite 4, Version: 4.4.0.RELEASE 运行没有问题,将项目中的静态资源和页面复制到 IDEA 的项目中,除了 IDE ...
- html学习(3)
为你的网页中添加一些空格 语法: 1 body> 2 <h1>感悟梦想</h1> 3 来源:作文网 作者:为梦想而飞 4 </body> 认识<h ...
- docker启动服务---------------nginx+php
环境 首先安装Docker,无论你是Windows还是Linux.MocOS都可以.安装Docker自行百度. Docker镜像源 访问https://hub.docker.com即可,它是镜像大仓库 ...
- 第十三章 Linux三剑客之老二—sed
一.sed #擅长增删改查 替换 选项: -n #取消默认输出 -r #支持扩展正则使用 -i #改变文件内容 -e #允许多项编辑 内部指令: p #print 打印 d # 删除 排除 a ...
- 浏览器页面左上角出现undefined
浏览器页面左上角出现undefined, js文档中: let list; list += html代码; 解决办法: let list = html代码;
- cgdb安装
cgdb官网:http://cgdb.github.io/ 一.cgdb安装 可使用wget命令下载,wget http://cgdb.me/files/cgdb-0.7.0.tar.gz 之后解压 ...
- 抽空学学KVM(六)qemu-img命令使用
通过KVM创建虚拟机,用到的命令不多,而且可以通过qemu-img -help查看到非常详细的解释,常用的主要有以下几种: 1.qemu-img info 查看磁盘信息 #info [-f ...