在《Vue3.x 從零開始(二)》中已經介紹了 Mixin 這種抽取公共邏輯的方式
但 Mixin 提供的資料或函式,無法在組件中直觀的體現出來
這導致組件的維護人員需要非常熟悉被引入的 Mixin 物件,不然出現重名的情況就容易出現意料之外的 bug
而 Composition API 是以函式的形式封裝公共邏輯,它通過顯式的回傳一個物件,讓開發人員能在組件中直接了解到被引入的欄位
一、簡單示例
假如某個組件需要在加載完成后,根據父組件傳入的引數來發送請求,并渲染請求結果:

這些邏輯可以直接提取為 mixin 物件,以達到復用的目的
也可以通過 Composition API 將這部分邏輯封裝成一個函式

在這個例子中,我們將相應的邏輯代碼都放到了 setup 函式中,它是 Composition API 的入口
setup 函式在組件創建之前就會觸發,最侄訓傳一個我們定義的物件,這個物件的欄位可以在組件的其他地方直接使用
比如上例中回傳了變數 list 和函式 fetchList,我們可以直接在組件的 methods 或者其他地方,通過 this.list 、this.fetchList 使用他們
在實際專案中,可以將上面的邏輯單獨封裝成一個函式并在 setup 中呼叫,最侄訓傳函式的回傳值
對比一下上面的兩段代碼,你應該會對 setup 有一個簡單的認識,接下來我會詳細介紹 setup 和 Composition API
二、生命周期和 setup
每個 Vue 組件都有一個屬于自己的生命歷程:
created(創建)-> mounted(加載)-> updated(更新)-> unmounted(卸載)
這些程序會對應一個鉤子函式,這些鉤子函式會在相應的階段觸發
上面只提到了四個生命周期,完整的生命周期可以參考《生命周期圖示》
// vue 2 中的 destroyed 和 beforeDestroy 鉤子在 vue 3 中被重命名為 unmounted 和 beforeUnmount
而 setup 函式是在決議其它組件選項之前,也就是 beforeCreate 之前執行


所以在 setup 內部,this 不是當前組件實體的參考,也就是說 setup 中無法直接呼叫組件的其他資料
如何在不能直接使用組件資料的前提下,完成組件的業務邏輯呢?
于是 Composition API 登場了,它讓我們能夠在 setup 中使用生命周期鉤子函式、回應式資料等組件特性
別急,這些內容待會兒就會介紹,目前還是先把 setup 弄清楚
1. setup 不是生命周期鉤子函式!
它只是基于 beforeCreate 運行,但函式內部無法通過 this 獲取組件實體
而且 setup 有著生命周期鉤子不具備的引數:props 和 context
setup(props, context) {
// 組件 props
console.log(props);
const { attrs, slots, emit } = context;
// Attribute (非回應式物件)
console.log(attrs);
// 組件插槽 (非回應式物件)
console.log(slots);
// 觸發事件 (方法)
console.log(emit);
}
這里的 props 就是組件內部定義的 props,是由父組件傳入的引數
假如父組件傳入了一個屬性名為 title 的 props,在 setup 中可以通過 props.title 直接取到
而且這個 props 是回應式的,當傳入新的 prop 時,props 會被更新
但正是因為 props 是回應式的,所以不能直接對 props 使用 ES6 解構,因為它會消除 prop 的回應性
Vue 3 提供了一個 toRefs 全域方法來解決這個問題:
import { toRefs } from 'vue';
setup (props) {
// 通過 toRefs 包裝后的 props 可以在 ES6 解構之后依然具有回應性
const { title } = toRefs(props);
console.log(title);
}
2. 在 setup 中注冊生命周期鉤子
如果是在 setup 內部注冊生命周期鉤子,則需要從 Vue 引入帶有 on 前綴的生命周期工具函式
import { toRefs, onMounted } from 'vue';
setup (props) {
// 使用 `toRefs` 創建對prop的 `title` property 的回應式參考
const { title } = toRefs(props);
// 注冊生命周期鉤子
onMounted(() => {
console.log('onMounted', title);
});
}
上面的 onMounted 會接收一個函式作為引數,在組件中對應的生命周期鉤子 (mounted) 觸發時,會執行這個被傳入的函式
除了 onMounted 以外,其他 created 之后的生命周期也有對應的注冊函式,如 onUpdated、onBeforeUnmount 等
但 setup 中并沒有 beforeCreate 和 created 這兩個生命周期的注冊函式
因為 setup 本身是基于 beforeCreate 運行,會用到 beforeCreate 和 created 的場景都可以通過 setup 替代
也就是說,在 beforeCreate 和 created 中撰寫的任何代碼都應該直接在 setup 函式中撰寫
3. setup 的回傳值
如果 setup 顯式的回傳了一個物件,這個物件的所有內容都會暴露給組件的其余部分
setup() {
return {
name: 'wise wrong',
foo: (text: string) => {
console.log(`Hello ${text}`);
},
};
},
mounted() {
// 直接使用 setup 的回傳值
this.foo(this.name);
},
上面的 setup 回傳了一個 foo 函式,還有一個 name 欄位,目前這個 name 還不是一個回應式變數
為此我們需要使用 ref 全域方法
import { ref } from 'vue';
setup (props) {
return {
name: ref('wise wrong');
}
}
通過 ref 包裝的變數會具有回應性,在組件中可以像正常的組件屬性一樣使用
但在 setup 內部,ref 包裝后的變數需要通過 value 來修改變數的值
import { ref } from 'vue';
setup() {
const name = ref('wise wrong');
onMounted(() => {
// 在 setup 內部通過 value 修改變數值
name.value = https://www.cnblogs.com/wisewrong/p/"Let's study Vue 3";
});
return {
name,
};
},
methods: {
test() {
// 在組件中可以直接修改 ref 變數
this.name = 'good job';
},
},
除了回傳一個物件以外,setup 還可以回傳一個渲染函式
import { h, ref, reactive } from 'vue'
export default {
setup() {
const readersNumber = ref(0)
const book = reactive({ title: 'Vue 3 Guide' })
// 回傳一個渲染函式以覆寫 template
return () => h('div', [readersNumber.value, book.title])
}
}
如果直接回傳了渲染函式,組件中定義的 template 將會失效
三、在 Setup 中使用 Computed、Watch
setup 的本意是用來替代 mixin,因此除了 data、methods、生命周期鉤子之外,還有許多組件選項需要解決
這里先介紹 computed 和 watch
1. Computed
在組件中 computed 用來管理包含回應式資料的復雜邏輯
computed: {
booksMessage() {
return this.books.length > 0 ? 'Yes' : 'No'
}
}
計算屬性可以在組件中直接使用,并會隨著回應式資料的更新而更新
<template>
<p>{{ booksMessage }}</p>
</template>
而在 setup 中,需要通過全域函式 computed 來包裝
import { ref, computed } from 'vue'
setup() {
const books = ref([]);
const booksMessage = computed(() => books.value.length > 0 ? 'Yes' : 'No');
return {
books,
booksMessage,
}
}
2. Watch
watch 用來監聽資料的變化
可以通過 watch 定義對應的處理函式,當資料發生變化時候會呼叫該函式
data: () => ({
question: '',
answer: 'good luck :)'
}),
watch: {
question(newQuestion, oldQuestion) {
// 當 question 變化的時候會執行該函式
if (newQuestion.indexOf('?') > -1) {
console.log('answer: ', this.answer);
}
}
},
在 setup 中,也需要使用全域函式 watch 來包裝
import { ref, watch } from 'vue'
setup() {
const question = ref('');
const answer = ref('good luck :)');
watch(question, (newValue, oldValue) => {
if (newValue.indexOf('?') > -1) {
console.log('answer: ', this.answer.value);
}
});
return {
question,
answer,
}
}
四、抽取公共邏輯
在了解了基本的 Composition API 之后,可以嘗試將公共邏輯抽取出來單獨維護
假設有以下兩個邏輯點需要被抽取:
1. 在組件加載完成后,通過父組件傳入的引數 query 請求資料串列 list,當 query 變化時需要重新請求并更新 list;
2. 根據關鍵字 keyword 從資料串列 list 中篩選資料,并使用 computed 記錄結果,
這兩段邏輯可以直接在 setup 中實作,但這樣會使得 setup 看起來非常累贅
我們可以把這段邏輯拆成兩個函式并單獨維護
首先在專案目錄 src 下創建一個新的檔案夾 composables
然后創建 useList.js 檔案,完成第一個邏輯:
// src/composables/useList.js
import { ref, onMounted, watch } from 'vue';
// 發起介面請求
function fetchList() {
// ...
}
export default function useList(query) {
// 創建資料串列 list (data)
const list = ref([]);
// 創建查詢并更新 list 的方法 (methods)
const getList = async () => {
list.value = await fetchList(query);
};
// 生命周期 mounted
onMounted(getList);
// 監聽 query 的變化并更新 list
watch(query, getList);
return {
list,
getList,
};
}
然后創建 useFilter.js 檔案,完成第二個邏輯:
// src/composables/useFilter.js
import { ref, computed } from 'vue';
export default function useList(list) {
// 創建搜索關鍵字 keyword (data)
const keyword = ref('');
// 創建篩選結果 filterRes (computed)
const filterRes = computed(() => {
return list.filter((value) => {
return value.includes(keyword.value);
});
});
return {
keyword,
filterRes,
};
}
然后在組件中引入,并在 setup 回傳組件需要的欄位
import { defineComponent, toRefs } from 'vue';
import useList from '@/composables/useList';
import useFiter from '@/composables/useFilter';
export default defineComponent({
props: ['query'],
setup(props) {
const { query } = toRefs(props);
const { list, getList } = useList(query);
const { keyword, filterRes } = useFiter(list);
return {
keyword, // 篩選關鍵字
getList, // 查詢并更新資料串列
list: filterRes, // 不需要回傳未經篩選的串列
};
},
});
這樣的代碼是不是更加清爽了呢?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/169665.html
標籤:JavaScript
上一篇:vue.js同一元素實作單擊click和雙擊事件dblclick,執行不同功能
下一篇:JavaScript輪播圖
