vue3—组合式API

参考:https://www.vue3js.cn/docs/zh/guide/composition-api-introduction.html(官网) 或 哔哩哔哩上 李南江老师的课

一、组件式API 介绍:

  1、setup 组件选项在创建组件之前执行,一旦 props 被解析,并充当合成 API 的入口点。

  2、执行 setup 时尚未创建组件实例,因此在 setup 选项中没有 this

  3、setup 中 返回的 { },里面的项 都会 挂在 组件对象【即this】下,组件的其余部分可用。

     注意:挂在 this 下的 变量 不一定是 响应式的,vue3中响应式的变量 必须通过给 API 创建。

  4、带 ref 的响应式变量:在 Vue 3.0 中,我们可以通过一个新的 ref 函数使任何响应式变量在任何地方起作用。

     注意:1、setup中要 使用 创建的 ref 变量,必须通过 .value 属性获取 或 赋值,才能响应式。

        2、ref函数只能监听简单类型的变化,不能监听复杂类型的变化(对象/数组)。复杂类型使用reactive

        const number = ref(10)
        console.log(number.value);

  5、reactive 的响应式变量:

  6、生命周期钩子注册内部 setup:  onMounted 生命周期

import { ref, onMounted } from 'vue'
setup (props) {
  const repositories = ref([])
  const getUserRepositories = async () => {
    repositories.value = await fetchUserRepositories(props.user)
  }

  onMounted(getUserRepositories)

  return {
    repositories,
    getUserRepositories
  }
}

  6、watch 响应式更改:

import { ref, watch } from 'vue'

const counter = ref(0)
watch(counter, (newValue, oldValue) => {
  console.log('The new counter value is: ' + counter.value)
})

  7、独立的 computed 属性:

import { ref, computed } from 'vue'

const counter = ref(0)
const twiceTheCounter = computed(() => counter.value * 2)

counter.value++
console.log(counter.value) // 1
console.log(twiceTheCounter.value) // 2

 

二、Setup:   https://vue3js.cn/docs/zh/guide/composition-api-setup.html

  1、使用 setup 函数时,它将接受两个参数:props、context

  

三、生命周期钩子:  https://vue3js.cn/docs/zh/guide/composition-api-lifecycle-hooks.html

四、提供/注入【多层组件嵌套时,数据的传递】:  https://vue3js.cn/docs/zh/guide/composition-api-provide-inject.html

五、模板引用:  https://vue3js.cn/docs/zh/guide/composition-api-template-refs.html

原文地址:https://www.cnblogs.com/wfblog/p/14298609.html