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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM