[TOC]

Composition API

vue2.x中,所有的数据都在data方法中定义返回,方法定义在methods下面,并通过this调用,vue3.x中,所有的代码逻辑将在setup方法中实现,包括datawatchcomputedmethodshooks,并且不再有this

vue3.x setup方法在组件生命周期内只执行一次,不会重复执行,setup会在beforeCreate中执行

getCurrentInstance 替代 this查找实例 (vue3不支持this)

  • vue3里面不会使用 this去寻找实例了,这里它提供了getCurrentInstance方法来获取实例
  • getCurrentInstance 只在setup()中生效 ```
``` ### 生命周期 > **2.x生命周期选项和Composition API之间的映射** - beforeCreate ->使用 setup() - created ->使用 setup() - beforeMount -> onBeforeMount - mounted -> onMounted - beforeUpdate -> onBeforeUpdate - updated -> onUpdated - beforeDestroy -> onBeforeUnmount - destroyed -> onUnmounted - errorCaptured -> onErrorCaptured ``` // vue3.x import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue' export default { setup() { onBeforeMount(() => { console.log('component is onBeforeMount') }) onMounted(() => { console.log('component is onMounted') }) onBeforeUpdate(() => { console.log('component is onBeforeUpdate') }) onUpdated(() => { console.log('component is onUpdated') }) onBeforeUnmount(() => { console.log('component is onBeforeUnmount') }) onUnmounted(() => { console.log('component is onUnmounted') }) } } ``` ### provide和inject(可能 你并不需要 vuex) - provide() 和 inject() 可以实现嵌套组件之间的数据传递 - 这两个函数只能在 setup() 函数中使用 - 父级组件中使用 provide() 函数向下传递数据 - 子级组件中使用 inject() 获取上层传递过来的数据 - provide inject实现父子传值的时候。子组件值更改也会影响父组件 > 如果父组件provide了 那么 他的所有的子孙等深层嵌套的组件都可以通过inject获取参数 - `父组件` ```vue ``` - `子组件` ```vue ``` - 注意: 如果不是父子孙等单一组件深层嵌套不建议使用(用的地方多的话,找起来太费劲) ### watch和watchEffect(监听属性) - `watch`跟`watchEffect`不同的地方在于,`watchEffect`注册后会立即调用,而`watch`默认不会,除非显示指定`immediate=true`,并且`watchEffect`可以停止监听 --- - ` watch `允许我们懒执行,也就是说仅在侦听的源变更时才执行回调,更明确哪些状态的改变会触发侦听器重新运行,访问侦听状态变化前后的值 - `watchEffect` 在响应式地跟踪其依赖项时立即运行一个函数,并在更改依赖项时重新运行他,无论值改变不改变刚加载时都会运行一次 ```

<a name="XEqu7"></a>
### script setup语法糖

- 在以 <script setup lang="ts">形式使用 setup时,默认整个 script都是setup的函数作用域,我们不必再一一 return定义的每个变量和方法,可以直接使用
- 但,对于 props、emit的定义,以及 ctx属性的获取问题 vue也针对此,为我们提供了3个新API
   - defineProps
   - defineEmit
   - useContext

// 这3个api和setup 的属性一一对应 setup(props, { emit, ctx}){}


- 如果想通过父组件获取子组件的属性,需要在子组件中通过 defineExpose定义需要暴露的属性

// 子组件 Child const count = ref(0) defineExpose({ count, });

// 父组件 // const ChildRef = ref>(0); const count = ChildRef.value.count ```

  • 官方文档写的很详细