vue3.0 学习
1.Composition API
1.新增setup() 执行时间是在以前 beforeCreate
和 created 之间
参数:
props: 获取父组件传递的参数
context :context参数包含attr,emit,slots ;该对象中包含了一些在vue 2.x
中需要通过 this
才能访问到属性
注意:在setup 函数内部无法访问2.X的this对象
2.生命周期以及其他vue的函数的使用需要按需引用
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, onErrorCaptured } from 'vue' export default { setup() { onBeforeMount(() => { // ... }) onMounted(() => { // ... }) onBeforeUpdate(() => { // ... }) onUpdated(() => { // ... }) onBeforeUnmount(() => { // ... }) onUnmounted(() => { // ... }) onActivated(() => { // ... }) onDeactivated(() => { // ... }) onErrorCaptured(() => { // ... }) } }
3.系统响应式API
1.reactive 2.ref 3.computed 4.watchEffect 5.watch 6.readOnly 7.toRefs
watchEffect : watchEffect()
函数接收一个函数作为第一个参数,并立即执行该函数,同时响应式追踪其依赖,并在其依赖变更时重新运行该函数,第二个参数为一个对象
function watchEffect( effect: (onInvalidate: InvalidateCbRegistrator) => void, options?: WatchEffectOptions ): StopHandle interface WatchEffectOptions { flush?: 'pre' | 'post' | 'sync' onTrack?: (event: DebuggerEvent) => void onTrigger?: (event: DebuggerEvent) => void } interface DebuggerEvent { effect: ReactiveEffect target: any type: OperationTypes key: string | symbol | undefined } type InvalidateCbRegistrator = (invalidate: () => void) => void type StopHandle = () => void
import { reactive, ref, computed, watchEffect, watch, readOnly } from "@vue-compositionAPI" setup(){ const state= reactive({count:0}); const test = ref(0); watchEffect(() => { console.log(count.value) }) watch( () => state.count, (count, prevCount) => { /* ... */ }) }
toRefs:函数可以将reactive()创建的响应式对象转换为普通对象,只不过这个对象上的每个属性节点都是ref()类型的响应式数据,配合v-model完成数据的双向绑定。
一般定义值是在setup中定义值,采用const state = reactive({xxx:xxx})的方式, 在最后采用return { ...toRefs(state)}的方式 ,让数据保持响应式