一、常用的Composition API
1. setup
-
vue3中一个新的配置项,值为一个函数。
-
setup是所有Composition API的容器,组合中用到的数据、方法等都需要在setup中配置。
-
setup函数的两种返回值:
- 若返回一个对象,那么对象中的属性、方法在模板中均可以直接使用。(常用)
- 若返回一个渲染函数,则可以自定义渲染内容。(了解)
-
在Vue2的配置项中可以访问到setup的数据,但是在setup当中不可以访问Vue2的数据;出现重名会优先显示setup定义的数据
-
setup前面不可以添加一个async,因为返回值不再是一个return的对象,而且是promise,模板看不到return对象中的属性;也可以返回一个Promise实例,但需要Suspence和异步组件配合
-
注意:
- setup执行的时机
- 在beforeCreate之前执行一次,this是undifined.
- setup的参数
- props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。
- context:上下文对象
- attrs 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性。
- slots 收到的插槽内容。
- emit 分发自定义事件的函数。
- setup执行的时机
2.ref函数
- 作用: 定义一个响应式的数据。
- 语法:
const data = ref(value)- 创建一个包含响应式数据的引用对象(reference对象,简称ref对象) 。
- JS中操作数据:
data.value。 - 模板中读取数据不需要data.value,直接:
<div>{{data}}</div>。
- 备注:
- 接收的数据类型:基本类型、对象类型。
- 基本类型:响应式依然是靠
Objec.defineProperty()的get和set去完成的。 - 对象类型:内部求助了一个函数——
reactive函数。
<template> <p>姓名:{{name}}</p> <p>年龄:{{age}}</p> <button @click='changeInfo'></button> </template> <script> import { defineComponent, reactive, computed } from "vue"; export default defineComponent({ setup(){ const name = ref('摩登兄弟刘宇宁') const age = ref(18) const changeInfo = ()=>{ name.value+='帅' age.value++ } return{ name, age, changeInfo } } }) </script>
3.reactive函数
- 作用:定义一个对象类型的响应式数据。
- 语法:
const data = reactive(源对象)- 接收一个对象或数组,
不能是基本类型。 - 返回一个代理对象(Proxy的实例对象,简称proxy对象)。
- 接收一个对象或数组,
- 备注:
- reactive定义的响应数据是'深层次的',
可以拦截对象中任意属性的变化(增删改)。 - 内部基于ES6的Proxy实现,通过代理对象操作源对象内部数据进行操作。
- reactive定义的响应数据是'深层次的',
<template>
<p>姓名:{{person.name}}</p>
<p>年龄:{{person.age}}</p>
<button @click='changeInfo'></button>
</template>
<script>
import { defineComponent, reactive, computed } from "vue";
export default defineComponent({
setup(){
const person = reactive({
name:'摩登兄弟刘宇宁',
age:'18'
})
const changeInfo = ()=>{
person.name+='帅'
person.value++
}
return{
person
changeInfo
}
}
})
</script>
4.reactive和ref的对比
- 从定义数据的角度对比
- ref用来定义:基本类型数据
- reactive用来定义:对象或数组数据类型
- 备注:ref也可以用来定义对象或数组的数据类型,它内部会自动通过
reactive转成代理对象
- 从原理角度对比
- ref通过类中的getter与setter来实现响应式数据劫持
- reactive通过Proxy来实现响应式,并通过Reflect操作源对象内部的数据
- 从使用角度对比
- ref定义的数据:操作数据需要.value,读取数据时模板中直接读取不需要.value.
- reactive定义的数据:操作数据与读取数据均不需要.value
5.响应式原理对比
- Vue2.x的响应式
- 实现原理
- 对象类型:通过Object.defineProperty()对属性的读取、修改进行拦截
- 数组类型:通过重写更新数组的一系列方法来实现拦截(对数组的变更方法进行了包裹)
let person = { name:'摩登兄弟刘宇宁', age:'18' } Object.keys(person).forEach(key=>{ Object.defineProperty(person, key, { get () { //读取时调用 return data[key] }, set (value) { //有人修改时调用 data[key] = value } }) }) - 存在问题
- 新增属性、删除属性,界面不会更新。
- 直接通过下边修改数组,界面不会自动更新。
- 解决方案
- 使用
Vue.set、Vue.delete或者vm.$set、vm.$delet这些API
- 使用
- 实现原理
- vue3.x的响应式
- 实现原理
- 通过Proxy代理:拦截对象中任意属性的变化,包括属性值的读写、属性的添加删除等。
- 通过Reflect反射:对源对象的属性进行操作
let person = { name:'摩登兄弟刘宇宁', age:'18' } const p = new Proxy(person,{ get(target,propName){ //读取时调用 return Reflect.get(target,propName) }, set(target,propName,value){//修改或新增时调用 rturn Reflect.set(target,propName,value) }, deleteProperty(target,propName){//删除时调用 return Reflect.deleteProperty(target,propName) } })
- 实现原理
6.computed计算属性
- 与Vue2.x中
computed配置功能一致 - 写法
<templat>
姓名:<input type='text' v-model='person.name'>
年龄:<input type='text' v-model='person.age'>
<p>
基本信息:<input v-model = 'person.fullInfo'>
</p>
</templat>
<script>
import { defineComponent, reactive, computed } from "vue";
export default defineComponent({
setup(){
const person = reactive({
name:'摩登兄弟刘宇宁',
age:'18',
})
//计算属性 —— 简写
person.fullInfo = computed(()=>{ return person.name + '-' + person.age })
//计算属性 —— 完整
person.fullInfo = computed({
get(){
return person.name + '-' + person.age
},
set(value){
const nameArr = value.split('-')
person.name = nameArr[0]
person.age = nameArr[1]
}
})
return {
person
}
}
})
</script>
7.watch监视
- 与Vue2.x中
watch配置功能一致 - 两个注意点
- watch监视reactive定义的响应式数据时,oldValue无法正确获取,强制开启了深度监视(depp = false无效)
- watch监视reactive定义的响应式数据中的某个对象属性时,deep配置有效。
- 备注
- 当watch监听ref数据时,
- 对于基本类型的数据,不需要.value这种方式去监听。
- 对于对象数据时,实际上借助了内部的reactive函数,也不需要取.value,只需要配置第三个配置对象内部的deep属性
- 当watch监听ref数据时,
- 总结
- 监听 直接定义的reactive对象无法获取正确的oldValue,并且deep失效
- 监听 通过ref定义的对象和reactive对象中的某个属性值为对象,无法获取正确的oldValue,但是deep生效
- 监听 基本类型oldValue可以正确获取
<template>
<h1>Watch监视</h1>
<p>ref定义的基本数据:{{ sum }}</p>
<button @click="sum++">点我+1</button>
<p>ref定义的对象数据:{{ message }}</p>
<button @click="message.color += '~'">点我改变颜色</button>
<hr />
<p>姓名:{{ person.name }}</p>
<p>年龄:{{ person.age }}</p>
<p>薪资:{{ person.job.star.money }}W</p>
<button @click="person.name += '帅'">姓名</button>
<button @click="person.age++">年龄</button>
<button @click="person.job.star.money += 10">薪资</button>
</template>
<script>
import { defineComponent, reactive, ref, watch } from "vue";
export default defineComponent({
setup() {
const sum = ref(0);
const message = ref({
color: "red",
});
const person = reactive({
name: "摩登兄弟刘宇宁",
age: 18,
job: {
star: {
money: 20,
},
},
});
//1.监听ref定义的单个数据
watch(
sum,
(newValue, oldValue) => {
console.log(newValue, oldValue); //1 0
},
{ immediate: true }
);
//2.1监听ref定义的对象数据
watch(
message.value,
(newValue, oldValue) => {
console.log(newValue, oldValue); //1 0
},
{ immediate: true }
);
//2.2监听ref定义的对象数据 需要加上deep进行深度监听,否则只监听第一层
watch(
message,
(newValue, oldValue) => {
console.log(newValue, oldValue); //1 0
},
{ deep: true }
);
//3监听ref定义的多个数据
watch(
[sum, message],
(newValue, oldValue) => {
console.log(newValue, oldValue); //[1, {color:red}],[0, {color:red}]
},
{
immediate: true,
deep: true, //如果不加deep = true 只能监听sum 无法监听message
}
);
//4.监视reactive定义的响应式数据
// 若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
// 若watch监视的是reactive定义的响应式数据,则强制开启了深度监视
// 若watch监视的是reactive定义的响应式数据中的某个属性,则deep有效
watch(
person,
(newValue, oldValue) => {
console.log("person变化了", newValue, oldValue);
},
{
immediate: true,
deep: false, //此处的deep配置不再奏效
}
);
watch(
() => person.job,
(newValue, oldValue) => {
console.log("person的job变化了", newValue, oldValue);
},
{
immediate: true,
deep: true, //此处的deep有效
}
);
watch(
() => person.job.star.money,
(newValue, oldValue) => {
console.log("person的job.star.money变化了", newValue, oldValue);
},
{ immediate: true, deep: true }
);
return {
sum,
message,
person,
};
},
});
</script>
8.watchEffect函数
- watchEffect函数不用指明监视哪个属性,而是监视的回调中用到哪些属性,就监视哪些属性。
- watchEffect和computed有些类似。
- computed更加注重的是计算出来的返回值
- watchEffect更注重的是过程,回调函数的函数体,不用写返回值
<template>
<h1>WatchEffect函数</h1>
<p>ref定义的基本数据:{{ sum }}</p>
<button @click="sum++">点我+1</button>
<p>ref定义的对象数据:{{ message }}</p>
<button @click="message.color += '~'">点我改变颜色</button>
</template>
<script>
import { defineComponent, reactive, ref, watchEffect } from "vue";
export default defineComponent({
setup() {
const sum = ref(0);
const message = reactive({
color: "red",
});
//1.监听ref定义的单个数据
watchEffect(() => {
const initSum = sum.value
const color = message.color
console.log('相关数据发生变化');
});
return {
sum,
message
};
},
});
</script>
7.toRef与toRefs的使用
- 作用:创建一个ref对象,其value值指向另外一个对象中的某个属性
- 语法:const name = toRef(person,'name').
- 应用:要将响应式对象中的某个属性单独提供给外部使用时。
- 扩展:
toRefs与toRef功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)
<template>
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
<button @click='changeInfo'></button>
</template>
<script>
import { defineComponent, reactive, toRefs, toRef } from "vue";
export default defineComponent({
setup(){
const person = reactive({
name:'摩登兄弟刘宇宁',
age:'18'
})
const changeInfo = ()=>{
person.name+='帅'
person.value++
}
const name = toRef(person,'name')
return{
...toRefs(person),
changeInfo
}
}
})
</script>
二、其他不常用CompositonAPI
1.shallowReactive 与 shallowRef 浅响应
- shallowReactive:只处理对象最外层属性的响应
- shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理
- 应用场景
- 如果有一个对象数据,结构比较深,变化时知识外层属性变化 ==》shallowReactive
- 如果有一个对象数据,后续功能不会修改对象中的属性,而是生成新的对象来替换 ==》 shallowRef 2.readOnly与shallowReadonly
- readonly:让一个响应式数据变为只读数据(深只读,嵌套的深层次数据不可以被修改)
- shallowReadonly:让一个响应式数据变为只读的(浅只读,嵌套的深层次数据可以被修改,第一层数据不可以被修改) 3.toRaw与markRaw
- toRaw 将一个有
reactive标记的响应式对象转变成一个普通对象,简单讲就是使这个对象丢失掉响应式- 应用场景:需要数据改变,但不引起页面更新的需求
- markRaw:标记一个对象,让其永远不会变为响应式对象
- 应用场景:有时需要我们给特定的响应式对象身上添加某个属性,但是不希望他是响应式的,所以就需要用到这个 4.customRef
- 创建一个自定义的ref,对其依赖项进行跟踪和触发进行控制
- 实现防抖效果
<template>
<input type="text" v-model="keyWord" />
<h3>{{ keyWord }}</h3>
</template>
<script>
import {defineComponent, customRef } from "vue";
export default defineComponent({
name: "App",
setup() {
//自定义一个ref——名为:myRef
function myRef(value, delay) {
let timer;
return customRef((track, trigger) => {
return {
get() {
console.log(`有人从myRef这个容器中读取数据了,我把${value}给他了`);
track(); // 通知Vue追踪value的变化(提前和get商量一下,让他认为这个value是有用的)
return value;
},
set(newValue) {
console.log(`有人把myRef这个容器中数据改为了:${newValue}`);
clearTimeout(timer);
timer = setTimeout(() => {
value = newValue;
trigger(); // 通知Vue去重新解析模板
}, delay);
},
};
});
}
// let keyWord = ref('hello') //使用Vue提供的ref
let keyWord = myRef("hello", 500); //使用程序员自定义的ref
return { keyWord };
},
});
</script>
5.provide与inject
- 使用
provide与inject来实现根组件与后代组件的通信,当然子组件也可以获取到provide所提供的数据,我们一般直接使用props就可以了 - 用法:
- 父组件 provide('通信名',通信数据)
- 子组件 const data = inject('通信名') 6.响应式数据的判断
- isRef: 检查一个值是否为一个 ref 对象
- isReactive: 检查一个对象是否是由 reactive 创建的响应式代理
- isReadonly: 检查一个对象是否是由 readonly 创建的只读代理
- isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理
三、新的组件
1.Fragment
- 在Vue2中: 组件必须有一个根标签
- 在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中
- 好处: 减少标签层级, 减小内存占用 2.Teleport
- 什么是Teleport?——
Teleport是一种能够将我们的组件html结构移动到指定位置的技术。
<teleport to="移动位置">
<div v-if="isShow" class="mask">
<div class="dialog">
<h3>我是一个弹窗</h3>
<button @click="isShow = false">关闭弹窗</button>
</div>
</div>
</teleport>
3.Suspense
- 等待异步组件时渲染一些额外内容,让应用有更好的用户体验 使用步骤:
- 异步引入组件
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>
- default:就是组件要显示的内容
- fallback:就是组件没加载完全的“备胎”
四、其他
1.全局API的转移
- Vue 2.x 有许多全局 API 和配置。
- 例如:注册全局组件、注册全局指令等。
- Vue3.0中对这些API做出了调整
- 将全局的API,即:
Vue.xxx调整到应用实例(app)上
- 将全局的API,即:
2.x 全局 API(Vue) | 3.x 实例 API (app) |
|---|---|
| Vue.config.xxxx | app.config.xxxx |
| Vue.config.productionTip | 移除 |
| Vue.component | app.component |
| Vue.directive | app.directive |
| Vue.mixin | app.mixin |
| Vue.use | app.use |
| Vue.prototype | app.config.globalProperties |
2.其他改变
-
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 的修饰符,同时也不再支持
config.keyCodes - 移除
v-on.native修饰符 - 移除过滤器(filter)
- 过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器。
参考
- Vue3官方文档 v3.cn.vuejs.org/
- Vite官方文档 cn.vitejs.dev/
- Vue-cli官方文档 cli.vuejs.org/zh/
- 尚硅谷Vue3视频 www.bilibili.com/video/BV1Zy…