1. Com API 简介Vue.js Com API 是 Vue 3 中引入的一组新的 API,旨在提供一种更加灵活和可组合的方式来组织和复用组件逻辑。它允许开发者以函数式编程风格来组织组件逻辑,从...
Vue.js Composition API 是 Vue 3 中引入的一组新的 API,旨在提供一种更加灵活和可组合的方式来组织和复用组件逻辑。它允许开发者以函数式编程风格来组织组件逻辑,从而提高代码的可读性、可维护性和复用性。
setup 函数是 Composition API 的核心,它在组件创建之前被调用。它接收 props 和 context 作为参数,用于访问组件的属性和上下文。在 setup 函数中,可以定义组件的响应式数据、计算属性、侦听器等。
import { ref, computed } from 'vue';
export default { setup() { const count = ref(0); const doubledCount = computed(() => count.value * 2); function increment() { count.value++; } return { count, doubledCount, increment }; }
};Composition API 提供了 ref 和 reactive 函数来创建响应式数据。
ref 用于创建单个值的响应式对象。reactive 用于创建对象类型的响应式对象。import { ref, reactive } from 'vue';
export default { setup() { const count = ref(0); const person = reactive({ name: 'John', age: 30 }); return { count, person }; }
};计算属性 (computed) 和侦听器 (watch) 可以用来处理数据的变化。
import { computed, watch } from 'vue';
export default { setup() { const count = ref(0); const doubledCount = computed(() => count.value * 2); watch(count, (newCount, oldCount) => { console.log(`Count changed from ${oldCount} to ${newCount}`); }); return { count, doubledCount }; }
};自定义指令可以用来封装 DOM 操作。
import { createApp } from 'vue';
const app = createApp({});
app.directive('focus', { mounted(el) { el.focus(); }
});
app.mount('#app');Vue 3 支持局部和全局组件。
// 局部组件
<template> <div> <my-component></my-component> </div>
</template>
<script>
import MyComponent from './MyComponent.vue';
export default { components: { MyComponent }
};
</script>
// 全局组件
import MyComponent from './MyComponent.vue';
const app = createApp({});
app.component('MyComponent', MyComponent);
app.mount('#app');Vue 3 提供了多种性能优化技术,如懒加载和代码分割。
// 懒加载组件
const MyLazyComponent = () => import('./MyLazyComponent.vue');
export default { components: { MyLazyComponent }
};使用 Axios 或 Fetch API 与后端进行交互。
import axios from 'axios';
export default { setup() { const fetchData = async () => { const response = await axios.get('/api/data'); console.log(response.data); }; fetchData(); }
};使用 Vuex 或 Vue 3 的 provide 和 inject 进行状态管理。
// Vuex
import { createStore } from 'vuex';
const store = createStore({ state() { return { count: 0 }; }, mutations: { increment(state) { state.count++; } }
});
// provide 和 inject
export default { setup() { const count = ref(0); provide('count', count); return { count }; }
};Vue.js Composition API 为开发者提供了一种更灵活和可组合的方式来组织和复用组件逻辑。通过使用 Composition API,可以更好地组织和维护大型应用,提高代码的可读性和可维护性。