在Vue3中,Composition API是一种新的API,它允许我们以函数的方式来使用Vue的功能,如响应式、生命周期钩子等。
- setup函数
setup函数是一个新的组件选项,作为Composition API的入口,它是在组件创建之前执行的。
import { defineComponent, ref } from 'vue';
 
export default defineComponent({
  setup() {
    const count = ref(0);
    // 更多的逻辑...
    return {
      count
    };
  }
});- reactive函数
reactive函数用于创建响应式对象,它可以是一个对象,也可以是一个数组。
import { defineComponent, reactive } from 'vue';
 
export default defineComponent({
  setup() {
    const state = reactive({
      count: 0
    });
 
    return {
      state
    };
  }
});- ref函数
ref函数用于创建一个响应式的引用对象,它是一个对象,里面包含一个.value属性。
import { defineComponent, ref } from 'vue';
 
export default defineComponent({
  setup() {
    const count = ref(0);
 
    return {
      count
    };
  }
});- toRefs函数
toRefs函数可以将reactive对象的属性转换为ref对象。
import { defineComponent, reactive, toRefs } from 'vue';
 
export default defineComponent({
  setup() {
    const state = reactive({
      count: 0,
      name: 'John'
    });
 
    return {
      ...toRefs(state)
    };
  }
});- computed函数
computed函数用于创建计算属性,它可以让我们定义一个依赖某些响应式属性的值,并且这个值是基于这些响应式属性计算出来的。
import { defineComponent, reactive, computed } from 'vue';
 
export default defineComponent({
  setup() {
    const state = reactive({
      count: 0,
      double: computed(() => state.count * 2)
    });
 
    return {
      state
    };
  }
});- watch函数
watch函数用于观察响应式属性的变化,并执行一些操作。
import { defineComponent, reactive, watch } from 'vue';
 
export default defineComponent({
  setup() {
    const state = reactive({ count: 0 });
 
    watch(() => state.count, (newValue, oldValue) => {
      console.log(`count changed from ${oldValue} to ${newValue}`);
    });
 
    return {
      state
    };
  }
});- watchEffect函数
watchEffect函数用于执行一些副作用的操作,它会在响应式属性发生变化时自动执行。
import { defineComponent, reactive, watchEffect } from 'vue';
 
export default defineComponent({
  setup() {
    const state = reactive({ count: 0 });
 
    watchEffect(() => {
      console.log(`count changed to ${state.count}`);
    });
 
    return {
      state
    };
  }
});- onMounted, onUnmounted, onUpdated, onRenderTracked, onRenderTriggered
这些函数用于