打包大小减少 41%
初次渲染快 55%, 更新渲染快 133%
内存减少 54%
…
使用 Proxy 代替 defineProperty 实现响应式
重写虚拟 DOM 的实现和 Tree-Shaking
…
Composition API(组合 API)
新的内置组件
其他改变
官方文档:https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create
## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
## 安装或者升级你的@vue/cli
npm install -g @vue/cli
## 创建
vue create vue_test
## 启动
cd vue_test
npm run serve
官方文档:https://v3.cn.vuejs.org/guide/installation.html#vite
vite官网:https://vitejs.cn


## 创建工程
npm init vite-app <project-name>
## 进入工程目录
cd <project-name>
## 安装依赖
npm install
## 运行
npm run dev
官方文档: https://v3.cn.vuejs.org/guide/composition-api-introduction.html
<template>
<h1>我是app组件h1>
<h1>我叫{{ name }}, {{ age }}岁h1>
<button @click="sayHello">hello!!button>
<h3>msg: {{ vue2 }}h3>
<p>数据冲突该怎么办?{{ a }}p>
<button @click="test1">测试一下在vue2中去读取vue3的配置button>
<button @click="test2">测试一下在vue3的setup中去读取vue2的配置button>
template>
<script>
// import { h } from 'vue';
export default {
name: "App",
//此处只是测试 setup,暂时先不考虑响应式的问题
//测试使用 vue2 的内容(可以读取到)
data() {
return {
vue2: "still can use vue2 in vue3 code",
a: 1,
};
},
methods: {
//vue2配置方法的方式
test1() {
console.log(this.vue2);
console.log(this.name);
console.log(this.sayHello);
this.sayHello();
},
},
setup() {
//表演的舞台
//准备数据 data
let name = "py";
let age = 21;
let a = 300;
//方法 methods
function sayHello() {
alert(`My name is ${name}, ${age} ${age === 1 ? "year" : "years"} old`);
}
//在 vue3 的配置里去读取 vue2 的属性
function test2() {
console.log(name);
console.log(age);
console.log(sayHello);
console.log(this.vue2); // 无法读取
console.log(this.test1); // 无法读取
}
//返回一个对象
return {
name,
age,
sayHello,
test2,
a,// 报错:vue2 vue3 都有 a,但最后的值以 vue3 为主
};
// 返回一个渲染函数
// 这是直接将你在这里渲染的东西替换到 template 中(以此渲染函数为主)
// return () => h('h1', 'hello');
},
};
script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
style>
const xxx = ref(initValue)
xxx.value.value,直接:{{ xxx }}Object.defineProperty()的get与set完成的。reactive函数<template>
<h1>我是app组件h1>
<h1>我叫{{ name }}, {{ age }}岁h1>
<h3>职位:{{ job.type }}h3>
<h3>薪水:{{ job.salary }}h3>
<button @click="changeInfo">修改人的信息button>
template>
<script>
import { ref } from "vue";
export default {
name: "App",
setup() {
// 表演的舞台(setup)
// 准备数据 data
// ref 实现响应式(基本类型)也是采用 Object.definedProperty() 来实现的 getter 和 setter
let name = ref("py"); //ref 引用对象
let age = ref(21);
// ref 实现响应式(对象类型)也是采用 Proxy 来实现
let job = ref({
type: "frontend developer",
salary: "30",
});
function changeInfo() {
name.value = "李四";
age.value = 42;
job.value.type = "UI developer";
}
//返回一个对象
return {
name,
age,
job,
changeInfo,
};
},
};
script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
style>
ref函数)const 代理对象= reactive(源对象)接收一个对象(或数组),返回一个代理对象(Proxy 的实例对象,简称 proxy 对象)<template>
<h1>我是app组件h1>
<h1>我叫{{ person.name }}, {{ person.age }}岁h1>
<h3>职位:{{ person.type }}h3>
<h3>薪水:{{ person.salary }}h3>
<h3>爱好:{{ person.hobbies }}h3>
<h4>测试的数据c:{{ person.a.b.c }}h4>
<button @click="changeInfo">修改人的信息button>
template>
<script>
import { reactive } from "vue";
export default {
name: "App",
setup() {
// 表演的舞台(setup)
// 准备数据 data
// ref 实现响应式(基本类型)也是采用 Object.definedProperty() 来实现的 getter 和 setter
// let name = ref('py'); //ref 引用对象(RefImpl)实例
// let age = ref(21);
// ref 实现响应式(对象类型)也是采用 Proxy 来实现(proxy) 这里如果就算是用 ref 也是借助了 reactive
let person = reactive({
name: "py",
age: 21,
type: "frontend developer",
salary: "30",
hobbies: ["抽烟", "喝酒", "烫头"],
a: {
b: {
c: 666,
},
},
});
function changeInfo() {
person.name = "李四";
person.age = 42;
// job.value.type = 'xxx'
person.type = "UI developer";
// 测试 reactive 能否监测深层次变化(可以监测到)
person.a.b.c = 100;
person.hobbies[0] = "play tennis"; // 可以监测到数组变化
}
//返回一个对象
return {
person,
changeInfo,
};
},
};
script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
style>
对象类型:通过Object.defineProperty()对属性的读取、修改进行拦截(数据劫持)
数组类型:通过重写更新数组的一系列方法来实现拦截(对数组的变更方法进行了包裹)
Object.defineProperty(data, 'count', {
get () {},
set () {}
})
new Proxy(data, {
// 拦截读取属性值
get(target, prop) {
return Reflect.get(target, prop);
},
// 拦截【设置】属性值 或【添加】新属性
set(target, prop, value) {
return Reflect.set(target, prop, value);
},
// 拦截删除属性
deleteProperty(target, prop) {
return Reflect.deleteProperty(target, prop);
},
});
proxy.name = "tom";
reactive转为代理对象Object.defineProperty()的get与set来实现响应式(数据劫持).value,读取数据时模板中直接读取不需要.value.valuethis.$attrsthis.$slotsthis.$emitHelloWorld.vue
<template>
<HelloWorld @hello="showHelloMsg" msg="你好啊" school="ABC">HelloWorld>
template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
name: "App",
setup() {
function showHelloMsg(value) {
alert(`你好啊,你触发了hello事件,我收到的参数是:${value}!`);
}
return { showHelloMsg };
},
components: { HelloWorld },
};
script>
App.vue
<template>
<h2>姓名:{{ person.name }}h2>
<button @click="test">测试触发一下HelloWorld组件的Hello事件button>
template>
<script>
import { reactive } from "@vue/reactivity";
export default {
name: "HelloWorld",
props: ['msg'], // 传几个写几个,不写全会报警告
emits:["hello"], // 不写能执行,但是会报警告
setup(props, context) {
let person = reactive({
name: "zs",
});
console.log('props-----',props);
console.log('context.attrs-----', context.attrs)
function test() {
context.emit("hello", "**子组件的信息**");
}
return { person,test };
},
};
script>
与 Vue2.x 中 computed 配置功能一致
写法
import { reactive, computed } from "vue";
setup(){
let person = reactive({
firstName: "pan",
lastName: "yue",
age: 21,
});
//计算属性——简写(没有考虑计算属性被修改的情况)
let fullName = computed(()=>{
return person.firstName + '-' + person.lastName
})
//计算属性——完整写法(既考虑了读也考虑了改)
let fullName = computed({
get(){
return person.firstName + '-' + person.lastName
},
set(value){
const nameArr = value.split('-')
person.firstName = nameArr[0]
person.lastName = nameArr[1]
}
})
}
与 Vue2.x 中 watch 配置功能一致
watch 的返回值:取消监听的函数
两个小“坑”:
setup() {
let sum = ref(0);
let msg = ref("你好");
let person = reactive({
name: "张三",
age: 18,
job: {
j1: {
salary: 20,
},
},
});
let person2 = ref({
name: "张三",
age: 18,
job: {
j1: {
salary: 20,
},
},
});
//情况一:监视 ref 定义的响应式数据
// 监测的不是一个值,而是一个保存值的结构(不能写成sum.value) 不能监视一个具体的值
watch(sum,(newValue,oldValue)=>{
console.log('sum变化了',newValue,oldValue)
},{immediate:true})
//情况二:监视多个 ref 定义的响应式数据
watch([sum,msg],(newValue,oldValue)=>{
console.log('sum或msg变化了',newValue,oldValue)
// 打印结果
// [1,'你好啊'] [0,'你好啊']
})
watch([sum,msg],(newValue,oldValue)=>{
console.log('sum或msg变化了',newValue,oldValue)
// 打印结果
// [0,'你好啊'] []
},{immediate:true})
/* 情况三:监视 reactive 定义的响应式数据
若 watch 监视的是 reactive 定义的响应式数据,则无法正确获得 oldValue!!
若 watch 监视的是 reactive 定义的响应式数据,则强制开启了深度监视,deep 配置不再奏效
*/
watch(person,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
},{immediate:true,deep:false}) //此处的 deep 配置不再奏效
// person2 是ref定义的
// 这里如果不是 person2.value 则会出现问题 因为 person2 是一个 RefImpl(默认没开启深度监视)
// 但是 person2.value 是一个借助了 proxy 生成的 reactive 响应式对象,所以这里可以解决问题
watch(person2.value,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
})
// person2 是 ref 定义的,所以也可以使用 deep 进行深度监听
watch(person2,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
},{deep:true})
//情况四:监视 reactive 定义的响应式数据中的某个属性
// oldValue 可以正常拿到
watch(()=>person.job,(newValue,oldValue)=>{
console.log('person的job变化了',newValue,oldValue)
})
//情况五:监视 reactive 定义的响应式数据中的某些属性
// oldValue 可以正常拿到
watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
console.log('person的job变化了',newValue,oldValue)
})
//特殊情况
// 如果这里的 job 是一个对象
// 此处由于监视的是 reactive 所定义的对象中的某个属性,所以 deep 配置有效
// 无法得到正常的 oldValue
watch(()=>person.job,(newValue,oldValue)=>{
console.log('person的job变化了',newValue,oldValue)
},{deep:true})
watch 的套路是:既要指明监视的属性,也要指明监视的回调
watchEffect 的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性
immediate:truewatchEffect 有点像 computed:
//watchEffect 所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
const stop = watchEffect(()=>{
const x1 = sum.value
const x2 = person.age
console.log('watchEffect配置的回调执行了')
})
vue2.x 的生命周期

vue3.0 的生命周期

beforeDestroy改名为 beforeUnmountdestroyed改名为 unmountedbeforeCreate ===> setup()created =======> setup()beforeMount ===> onBeforeMountmounted =======> onMountedbeforeUpdate ===> onBeforeUpdateupdated =======> onUpdatedbeforeUnmount ==> onBeforeUnmountunmounted =====> onUnmounted<template>
<h1>当前求和为:{{ sum }}h1>
<button @click="sum++">点我加一button>
<hr/>
template>
<script>
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';
export default {
name: 'Demo',
setup(){
let sum = ref(0);
//通过组合式 api 的形式去使用生命周期钩子
///setup() 相当于 beforeCreate() 和 created()
onBeforeMount(() => { console.log('----beforeMount----'); });
onMounted(() => { console.log('-----mounted-----'); });
onBeforeUpdate(() => { console.log('-----beforeUpdate-----') });
onUpdated(() => { console.log('-----updated-----'); });
onBeforeUnmount(() => { console.log('-----beforeUnmount----'); });
onUnmounted(() => { console.log('-----unmounted----'); })
console.log('-----setup----')
//返回一个对象
return {
sum,
}
},
//使用配置项的形式使用生命周期钩子
// beforeCreate() {
// console.log('在组件实例初始化完成之后立即调用');
// },// 配置项独有
// created() {
// console.log('在组件实例处理完所有与状态相关的选项后调用');
// },// 配置项独有
// beforeMount() {
// console.log('在组件被挂载之前调用');
// },
// mounted() {
// console.log('在组件被挂载之后调用');
// },
// beforeUpdate() {
// console.log('在组件即将因为一个响应式状态变更而更新其 DOM 树之前调用')
// },
// updated() {
// console.log('在组件因为一个响应式状态变更而更新其 DOM 树之后调用');
// },
// beforeUnmount() {
// console.log('在一个组件实例被卸载之前调用');
// },
// unmounted() {
// console.log('在一个组件实例被卸载之后调用');
// }
}
script>
<style>
style>
创建一个 hooks 文件夹,里面创建文件 usePoint.js
// usePoint.js
// 得到鼠标点的 api
import { reactive, onMounted, onBeforeUnmount } from "vue";
export default function() {
//实现鼠标“打点”相关的数据
let point = reactive({
x: 0,
y: 0,
});
//实现鼠标“打点”相关的方法
function savePoint(event) {
point.x = event.pageX;
point.y = event.pageY;
console.log(event.pageX, event.pageY);
}
//实现鼠标“打点”相关的生命周期钩子
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeUnmount(() => {
window.removeEventListener("click", savePoint);
});
return point;
}
<template>
<h2>我是HelloWorld组件h2>
<h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}h2>
template>
<script>
import usePoint from '../hooks/usePoint'
export default {
name:'HelloWorld',
setup(){
const point = usePoint()
return {point}
}
}
script>
const name = toRef(person,'name')toRefs与toRef功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person),虽然只拆第一层属性,但不影响响应式的深度<template>
<h4>{{ person }}h4>
<h2>姓名:{{ name }}h2>
<h2>年龄:{{ age }}h2>
<h2>薪资:{{ salary }}Kh2>
<button @click="name = name + '~'">修改姓名button>
<button @click="age++">增长年龄button>
<button @click="salary++">增长薪资button>
template>
<script>
import { reactive, toRef, toRefs } from 'vue';
export default {
name: 'Demo',
setup(){
let person = reactive({
name: '张三',
age: 18,
job:{
j1:{
salary: 20
}
}
});
// ref 类型的值在模板里使用是不需要 .value 来取的
const name1 = person.name //注意输出字符串,并不是响应式的数据
console.log('@@@@@', name1);
// RefImpl 这里的 name2 与 person.name 是完全一模一样的
// 改这里的 name2 与你改 person.name 是一码事,且数据还是响应式的
const name2 = toRef(person,'name');
console.log('####', name2);
const x = toRefs(person);
console.log(x);
//返回一个对象(toRef 是引用 name 就是 person.name 且为响应式)
//toRef 处理一个,而 toRefs 处理一群
//大白话:toRef(s) 就是方便我们把响应式数据(ref,reactive)展开丢出去,方便在模版中应用
return {
person,
// name: toRef(person, "name"),
// age: toRef(person, "age"),
// salary: toRef(person.job.j1, "salary")
...toRefs(person),
salary: toRef(person.job.j1, 'salary') //toRef 可以与 toRefs 连用,更加方便
};
// 注意千万不能这样写
// 一旦这样写就与原数据分离了,
// 改 name 不会引起 person.name 的变化(因为 ref把 name 值包装成了另一个refImpl对象
// return {
// person,
// name: ref(person.name),
// age: ref(person.age),
// salary: ref(person.job.j1.salary)
// };
}
}
script>
<style>
style>
shallowReactive:只处理对象最外层属性的响应式(浅响应式)
shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理
什么时候使用?
<template>
<h2>当前求和为:{{ sum }}h2>
<button @click="sum++">sum+1button>
<hr/>
<h2>姓名:{{ name }}h2>
<h2>年龄:{{ age }}h2>
<h2>薪资:{{ job.j1.salary }}Kh2>
<button @click="name = name + '~'">修改姓名button>
<button @click="age++">增长年龄button>
<button @click="job.j1.salary++">增长薪资button>
template>
<script>
import {ref,reactive, toRefs, readonly, shallowReadonly} from 'vue';
export default {
name: 'Demo',
setup(){
let sum = ref(0);
let person = reactive({
name: '张三',
age: 18,
job:{
j1:{
salary: 20
}
}
});
person = readonly(person); //此时 person 里面的属性值都不允许修改
person = shallowReadonly(person); //第一层不能改(name,age), 但 j1 和 salary 仍然可以改动
sum = readonly(sum); //同理
sum = shallowReadonly(sum)
return {
sum,
...toRefs(person),
};
}
}
script>
<style>
style>
reactive生成的响应式对象转为普通对象作用:创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制
实现防抖效果
<template>
<input type="text" v-model="keyWord" />
<h3>{{ keyWord }}h3>
template>
<script>
import { customRef } from "vue";
export default {
name: "App",
setup() {
//自定义一个ref——名为:myRef
function myRef(value, delay) {
let timer;
return customRef((track, trigger) => {
return {
get() {
console.log(`有人从myRef这个容器中读取数据了,我把${value}给他了`);
// 通知Vue追踪value的变化(提前和get商量一下,让他认为这个value是有用的)
track();
return value;
},
set(newValue) {
console.log(`有人把myRef这个容器中数据改为了:${newValue}`);
clearTimeout(timer);
timer = setTimeout(() => {
value = newValue;
trigger(); // 通知Vue去重新解析模板
}, delay);
},
};
});
}
let keyWord = myRef("hello", 500); //使用程序员自定义的ref
return { keyWord };
},
};
script>

provide 选项来提供数据,后代组件有一个 inject 选项来开始使用这些数据祖组件中
import {reactive, provide} from "vue";
...
setup(){
......
let car = reactive({name:'奔驰',price:'40万'})
provide('car',car) // 给自己的后代组件传递数据
......
}
后代组件中
import { inject } from "vue";
...
setup(props,context){
......
const car = inject('car') // 拿到祖先的数据
return {car}
......
}
reactive 创建的响应式代理readonly 创建的只读代理
reactive 或者 readonly 方法创建的代理import {reactive, isReactive} from "vue";
...
setup(){
......
let car = reactive({name:'奔驰',price:'40万'})
console.log(isReactive(car)) // true
......
}
使用传统 OptionsAPI 中,新增或者修改一个需求,就需要分别在 data,methods,computed 里修改
Teleport 是一种能够将我们的组件 HTML 结构移动到指定位置的技术<teleport to="移动位置(html、body、css选择器)">
<div v-if="isShow" class="mask">
<div class="dialog">
<h3>我是一个弹窗h3>
<button @click="isShow = false">关闭弹窗button>
div>
div>
teleport>
异步引入组件
// 作用:定义一个异步组件
import { defineAsyncComponent } from 'vue'
// 动态引入(异步引入)
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
使用Suspense包裹组件,并配置好default与 fallback
<template>
<div class="app">
<h3>我是App组件h3>
<Suspense>
<template v-slot:default>
<Child/>
template>
<template v-slot:fallback>
<h3>加载中.....h3>
template>
Suspense>
div>
template>


Suspense的另一种玩法
...
async setup() {
let sum = ref(0);
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
sum
});
},5000)
})
return await p;
}
Vue 2.x 有许多全局 API 和配置
//注册全局组件
Vue.component('MyButton', {
data: () => ({
count: 0
}),
template: ''
})
//注册全局指令
Vue.directive('focus', {
inserted: el => el.focus()
}
Vue3.0 中对这些 API 做出了调整
Vue.xxx调整到应用实例(app)上2.x 全局 API(Vue) | 3.x 实例 API (app) |
|---|---|
| Vue.config.xxxx | app.config.xxxx |
| Vue.config.productionTip(关闭vue的生产提示) | 移除 |
| Vue.component | app.component |
| Vue.directive | app.directive |
| Vue.mixin | app.mixin |
| Vue.use | app.use |
| Vue.prototype | app.config.globalProperties |
data 选项应始终被声明为一个函数
过度类名的更改
Vue2.x 写法
.v-enter,
.v-leave-to {
opacity: 0;
}
.v-leave,
.v-enter-to {
opacity: 1;
}
Vue3.x 写法
.v-enter-from,
.v-leave-to {
opacity: 0;
}
.v-leave-from,
.v-enter-to {
opacity: 1;
}
移除 keyCode 作为 v-on 的修饰符(例:@keyup.13),同时也不再支持config.keyCodes
移除 v-on.native修饰符
父组件中绑定事件
<my-component
v-on:close="handleComponentEvent"
v-on:click="handleNativeClickEvent"
/>
子组件中声明自定义事件
<script>
export default {
emits: ['close']
}
script>
过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器