组合式Api-setup/ref/reactive
官方文档:
https://composition-api.vuejs.org/zh/api.html
1. Composition Api(setup/ref/reactive)
1) setup的细节
- setup的基本用法
<template>
<!-- vue2中,html模版中必须要有一对根标签 / vue3组件的html模版中可以没有根标签 -->
<h1>hello Vue3</h1>
<h1>{{ number }}</h1>
</template>
<script lang="ts">
//defineComponent函数, 目的是定义一个组件,内部可以传入一个配置对象
import { defineComponent } from 'vue';
export default defineComponent({
// 当前组件的名字
name: 'App',
// 注册一个子级组件
components: {
},
// 测试代码 - setup组合api中第一个要使用的函数
setup(){
console.log('hello Vue3')
let number =10
return {
number
}
},
});
</script>
- setup 执行的时机
- 在beforeCreate之前执行(只执行一次), 此时组件对象还没有创建,此时this是undefined, 不能通过this来访问data/computed/methods / props,并且所有的composition API相关回调函数中也都不可以访问。
- setup的返回值
- 一般都返回一个对象: 为模板提供数据, 也就是模板中可以直接使用此对象中的所有属性/方法
返回对象中的属性会与data函数返回对象的属性合并成为组件对象的属性
返回对象中的方法会与methods中的方法合并成功组件对象的方法
如果有重名, setup优先
注意:
- 一般不要混合使用: methods中可以访问setup提供的属性和方法, 但在setup方法中不能访问data和methods
- setup不能是一个async函数: 因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性数据
2) reactive与ref-细节
- ref
作用: 定义一个数据的响应式(一般用来定义一个基本类型的响应式数据
)
语法:const xxx = ref(initValue)
基本用法:
<template>
<-- 模板中操作数据: 不需要.value -->
<div>{{ count }}</div>
<button @click="updateCount">点击</button>
</template>
<script lang="ts">
import { defineComponent,ref } from 'vue';
export default defineComponent({
// 当前组件的名字
name: 'App',
// 需求:页面打开的时候可以直接显示数据,点击按钮后,该数据可以发生变化
setup(){
// 创建一个包含响应式数据的引用(reference)对象
const count = ref(0)
function updateCount(){
//js中操作数据: xxx.value
count.value++
}
// 内部返回的是一个对象
return{
count,
updateCount: updateCount
}
},
});
</script>
- reactive
作用:定义多个数据的响应式
语法:const proxy = reactive(obj)
基本用法:
<template>
<h2>reactive的使用</h2>
<h3>名字:{{ user.name }}</h3>
<h3>年龄:{{ user.age }}</h3>
<h3>性别:{{ user.gender }}</h3>
<h3>对象:{{ user.wife }}</h3>
<hr>
<button @click="updateUser">更新数据</button>
</template>
<script lang="ts">
import {defineComponent, reactive} from 'vue';
export default defineComponent({
// 当前组件的名字
name: 'App',
setup() {
// const obj: any = { // 为了使用obj.gender = '男'
const obj = {
name: "小草",
age: 20,
wife: {
name: '小花',
age: 18,
cars: ['奔驰', '宝马', '奥迪']
}
}
// 接收一个普通对象然后返回该普通对象的响应式代理器对象
/*
响应式转换是“深层的”:会影响对象内部所有嵌套的属性
内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据都是响应式的
*/
const user = reactive<any>(obj)
const updateUser = () => {
user.name = '小叶'
user.age = 30
user.wife.cars[0] = '玛莎拉蒂'
}
// 内部返回的是一个对象
return {
user,
updateUser
}
},
});
</script>
总结*
reactive与ref是Vue3的 composition API中2个最重要的响应式API
用来处理基本类型数据, reactive用来处理对象(递归深度响应式) 如果用ref对象/数组,
内部会自动将对象/数组转换为reactive的代理对象 ref内部: 通过给value属性添加getter/setter来实现对数据的劫持
reactive内部: 通过使用Proxy来实现对对象内部所有数据的劫持, 并通过Reflect操作对象内部数据 ref的数据操作:
在js中要.value, 在模板中不需要(内部解析模板时会自动添加.value)
The end…
如果您认真阅读至此,您现在已经掌握了setup和ref和reactive啦 ,为接下来我们学习Vue3更加有信心!!。
如果喜欢这个帖子,请不要忘记点赞,留言,评论。我们一起在前端小白中进步