Composition API optimization techniques
Composition API is one of the core features of Vue 3, offering a more flexible way to organize and reuse logic. Compared to Options API, Composition API leverages functional programming to make code clearer and easier to maintain. Here are some optimization techniques to help you better utilize Composition API and improve development efficiency.
Splitting Logic into Custom Hooks
Encapsulating related logic into custom hooks can significantly enhance code readability and reusability. For example, form validation logic can be extracted into a standalone hook:
// useFormValidation.js
import { ref, computed } from 'vue';
export function useFormValidation() {
const username = ref('');
const password = ref('');
const isUsernameValid = computed(() => username.value.length >= 3);
const isPasswordValid = computed(() => password.value.length >= 6);
return {
username,
password,
isUsernameValid,
isPasswordValid,
};
}
When using it in a component, simply import and call:
import { useFormValidation } from './useFormValidation';
export default {
setup() {
const { username, password, isUsernameValid, isPasswordValid } = useFormValidation();
return {
username,
password,
isUsernameValid,
isPasswordValid,
};
},
};
Using reactive
Instead of Multiple ref
s
When managing multiple related states, reactive
is more concise than multiple ref
s. For example:
import { reactive } from 'vue';
const state = reactive({
count: 0,
name: 'Vue 3',
isActive: false,
});
// Modify state
state.count++;
state.name = 'Composition API';
Leveraging watch
and watchEffect
for Efficient Change Tracking
watch
and watchEffect
are powerful tools in Composition API for tracking state changes. watch
is ideal for precisely observing specific values, while watchEffect
automatically tracks dependencies.
import { ref, watch, watchEffect } from 'vue';
const count = ref(0);
// Precisely watch count changes
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
// Automatically track dependencies
watchEffect(() => {
console.log(`count value is ${count.value}`);
});
Optimizing Derived State with computed
Derived state can be cached using computed
to avoid redundant calculations. For example:
import { ref, computed } from 'vue';
const price = ref(100);
const quantity = ref(2);
const total = computed(() => price.value * quantity.value);
console.log(total.value); // 200
Handling Asynchronous Logic in Composable Functions
When dealing with asynchronous logic in composable functions, combine async/await
with ref
or reactive
:
import { ref } from 'vue';
export function useFetchData(url) {
const data = ref(null);
const error = ref(null);
const isLoading = ref(false);
async function fetchData() {
isLoading.value = true;
try {
const response = await fetch(url);
data.value = await response.json();
} catch (err) {
error.value = err;
} finally {
isLoading.value = false;
}
}
return {
data,
error,
isLoading,
fetchData,
};
}
Using provide
and inject
for Cross-Component State Sharing
Composition API's provide
and inject
can replace Vuex for state sharing in small applications:
// Parent component
import { provide, reactive } from 'vue';
export default {
setup() {
const sharedState = reactive({
theme: 'dark',
user: { name: 'Alice' },
});
provide('sharedState', sharedState);
},
};
// Child component
import { inject } from 'vue';
export default {
setup() {
const sharedState = inject('sharedState');
return {
sharedState,
};
},
};
Destructuring Reactive Objects with toRefs
Directly destructuring a reactive
object loses reactivity, but toRefs
solves this:
import { reactive, toRefs } from 'vue';
const state = reactive({
count: 0,
name: 'Vue',
});
const { count, name } = toRefs(state);
// Now count and name remain reactive
Performance Optimization: Avoid Unnecessary Reactive Conversions
Wrapping non-reactive data as ref
or reactive
adds overhead. For example, static configuration data can use plain objects:
// No need for reactivity
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000,
};
// Needs reactivity
const state = reactive({
loading: false,
data: null,
});
Lifecycle Hooks in Composable Functions
Using lifecycle hooks directly in composable functions allows more flexible side-effect management:
import { onMounted, onUnmounted } from 'vue';
export function useEventListener(target, event, callback) {
onMounted(() => {
target.addEventListener(event, callback);
});
onUnmounted(() => {
target.removeEventListener(event, callback);
});
}
Type Inference and TypeScript Support
Composition API works seamlessly with TypeScript. Generics and interfaces enhance type safety:
import { ref } from 'vue';
interface User {
id: number;
name: string;
}
const user = ref<User>({
id: 1,
name: 'Alice',
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:SPA应用性能优化全流程
下一篇:响应式性能最佳实践