性能层面
- 双向绑定原理由
Object.defineProperty
改为基于ES6的Proxy
,使其颗粒度更大,速度更快。 - 重写了
Vdom
,突破了Vdom
的性能瓶颈 - 编译优化,更高效的组件初始化组件
(diff方法优化,hoistStatic 静态提升,cacheHandlers 事件侦听器缓存,ssr渲染等) - 加强了对ts的支持
新增功能
1. setup函数
意义:相关业务的代码放在不同的配置项中,不利于维护,于是就有了setup函数(简单说就是可以把相关代码放在一起)
执行顺序:beforeCreate
之前
实例:
/*
注意事项:
1. setup 中没有this
2. setup 函数中的 props 是响应式的,不能使用 ES6 解构,解构必须是使用toRefs()
3. setup函数只能是同步的不能是异步的
*/
// composition-api,setup中使用
import { ref, reactive, toRefs, isRef, computed, watchEffect, watch } from 'vue'
/*
各composition-api使用场景:
ref,reactive主要定义响应式数据
ref 主要定义字符串,数字,数组,bool,可以根据给定的值来创建一个响应式的数据对象,返回值是一个对象
reactive 主要定义对象
toRefs 解构对象
isRef 用来判断某个值是否为 ref() 创建出来的响应式的值
computed 计算属性,同vue的computed
watchEffect,watch 监听(watchEffect:会立即执行传入的函数,并响应式侦听其依赖;watch:默认情况下初次渲染不执行,同vue的watch)
readonly 对象只读(数据不再响应式)
setup中可以写生命周期函数
*/
setup(){
// ref使用
const str = ref('字符串');
console.log(str.value)
// reactive使用
const jsons = reactive({
title: 'vue3.0',
desc: '学习资料'
})
console.log(jsons.desc)
// toRefs使用
const { title } = toRefs(jsons)
console.log(title.value)
// isRef使用
const isStr = isRef(str) ? str.value : str
console.log(isStr)
// computed使用
const studyT = computed(()=>{
return `今天的${jsons.desc}是${jsons.title}`
})
// watchEffect 会监听jsons.title与其相关依赖
const watchE = watchEffect(()=>{
console.log(jsons.title)
})
// watch使用
watch(studyT /*改变的参数*/,()=>{
// 执行的操作
})
// 方法定义
const getData = ()=>{
console.log(jsons.desc)
}
// 最后必须return出去
return{
str,
jsons,
studyT,
watchE,
getData
}
}
2. Provide/Inject
使用场景:父组件给子组件和孙子组件传值
实例:
// 父组件
import { provide } from 'vue'
setup(){
provide('title', '123456')
}
// 子组件
export default {
inject:['title'] //可以直接在模板中使用
}
3. Teleport
作用:可以将html节点渲染的内容传送到任何指定的地方
实例:
<teleport to="body"> //渲染到body节点下
</teleport>
4. Suspense
作用:处理异步显示问题
实例:刚开始会渲染一个 fallback
状态下的内容,直到到达某个条件后才会渲染 default
状态的正式内容
<suspense>
<template #default>
<NewSuspense></NewSuspense>
</template>
<template #fallback>
<h1>Loadding...</h1>
</template>
</suspense>
5. 变量可以在style中使用
export default {
data(){
return{
colors: 'red',
font:{
size: '2em'
}
}
}
}
<style scoped>
#composition{
color: v-bind(colors);
font-size: v-bind('font.size');
}
</style>
6. template可以写多个根节点
<template>
<span></span>
<span></span>
</template>
TS 兼容
/*
1. script添加 lang = ts
2. 引入 defineComponent
*/
// 实例
<script lang="ts">
import { defineComponent } from 'vue';
// 定义一个接口
interface Inter{
title:string,
count: number,
}
// 实现接口
const newData = {
title: '我是一个标题',
count: 12.23
} as Inter;
export default defineComponent({
setup(){
let data:Inter = reactive({
title: '张三',
count: 14,
})
return data
},
//data使用
data(){
return newData,
},
});
</script>