Vue 3 提供了丰富的 API,支持组件开发、响应式数据管理和生命周期控制。本节整理了 Vue 3 的常用 API,包括 Composition API、Options API 和指令等,旨在为开发者提供快速参考。以下内容按功能分类,包含简要说明和示例,帮助你在开发中快速查找和应用。
| API | 描述 | 示例 |
|---|
setup() | 组件逻辑的入口,取代 data 和 methods | <script>export default { setup() { return { count: ref(0) } } }</script> |
ref() | 创建响应式引用,适用于单一值 | const count = ref(0); count.value++ |
reactive() | 创建深层响应式对象 | const state = reactive({ count: 0 }) |
computed() | 创建计算属性,支持 getter/setter | const double = computed(() => count.value * 2) |
watch() | 监听响应式数据变化 | watch(count, (newVal) => console.log(newVal)) |
<script>
import { ref, computed, watch } from 'vue';
export default {
setup() {
const count = ref(0);
const double = computed(() => count.value * 2);
watch(count, (newVal) => console.log('Count:', newVal));
const increment = () => count.value++;
return { count, double, increment };
}
};
</script>
| API | 对应 Options API | 描述 | 示例 |
|---|
onBeforeMount | beforeMount | 组件挂载前 | onBeforeMount(() => console.log('Before Mount')) |
onMounted | mounted | 组件挂载后 | onMounted(() => console.log('Mounted')) |
onBeforeUpdate | beforeUpdate | 数据更新前,DOM 未刷新 | onBeforeUpdate(() => console.log('Before Update')) |
onUpdated | updated | 数据更新后,DOM 已刷新 | onUpdated(() => console.log('Updated')) |
onBeforeUnmount | beforeUnmount | 组件卸载前 | onBeforeUnmount(() => console.log('Before Unmount')) |
onUnmounted | unmounted | 组件卸载后 | onUnmounted(() => console.log('Unmounted')) |
<script>
import { onMounted, onUnmounted } from 'vue';
export default {
setup() {
onMounted(() => console.log('Component Mounted'));
onUnmounted(() => console.log('Component Unmounted'));
}
};
</script>
| API | 描述 | 示例 |
|---|
shallowRef() | 创建浅层响应式引用 | const shallow = shallowRef({ count: 0 }) |
shallowReactive() | 创建浅层响应式对象 | const shallow = shallowReactive({ count: 0 }) |
readonly() | 创建只读代理 | const readOnly = readonly(ref(0)) |
toRefs() | 将 reactive 对象转为 refs | const state = reactive({ count: 0 }); const { count } = toRefs(state) |
markRaw() | 标记对象为非响应式 | const raw = markRaw({ data: 'raw' }) |
| 选项 | 描述 | 示例 |
|---|
data | 定义响应式数据 | data: () => ({ count: 0 }) |
methods | 定义组件方法 | methods: { increment() { this.count++ } } |
computed | 定义计算属性 | computed: { double() { return this.count * 2 } } |
watch | 监听数据变化 | watch: { count(newVal) { console.log(newVal) } } |
props | 定义组件属性 | props: { initial: Number } |
emits | 声明自定义事件 | emits: ['update'] |
<script>
export default {
props: { initial: Number },
data: () => ({ count: 0 }),
computed: {
double() { return this.count * 2; }
},
methods: {
increment() { this.count++; }
},
watch: {
count(newVal) { console.log('Count:', newVal); }
}
};
</script>
| 指令 | 描述 | 示例 |
|---|
v-bind | 绑定属性(简写 :attr) | <div :class="className"></div> |
v-on | 绑定事件(简写 @event) | <button @click="increment">Click</button> |
v-model | 双向绑定 | <input v-model="text" /> |
v-if | 条件渲染 | <div v-if="show">Visible</div> |
v-for | 列表渲染 | <li v-for="item in items" :key="item.id">{{ item }}</li> |
v-show | 显示/隐藏元素 | <div v-show="visible">Shown</div> |
v-once | 只渲染一次 | <p v-once>{{ staticText }}</p> |
v-memo | 缓存渲染(Vue 3.2+) | <div v-memo="[value]">Cached</div> |
<template>
<div>
<input v-model="text" :placeholder="placeholder" />
<ul>
<li v-for="item in items" :key="item.id" v-show="item.active">{{ item.name }}</li>
</ul>
<p v-if="show" v-once>{{ message }}</p>
<button @click="toggle">Toggle</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const text = ref('');
const placeholder = ref('Enter text');
const items = ref([{ id: 1, name: 'Item 1', active: true }]);
const show = ref(true);
const message = ref('Static Message');
const toggle = () => (show.value = !show.value);
return { text, placeholder, items, show, message, toggle };
}
};
</script>
| API | 描述 | 示例 |
|---|
createApp() | 创建 Vue 应用实例 | const app = createApp(App) |
app.mount() | 挂载应用到 DOM | app.mount('#app') |
app.use() | 安装插件 | app.use(router) |
app.component() | 注册全局组件 | app.component('MyComp', MyComp) |
app.config.globalProperties | 添加全局属性 | app.config.globalProperties.$http = axios |
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
| 组件/工具 | 描述 | 示例 |
|---|
<Teleport> | 将内容传送到指定 DOM | <Teleport to="body"><div>Modal</div></Teleport> |
<Suspense> | 处理异步组件加载(实验性) | <Suspense><AsyncComp /></Suspense> |
defineAsyncComponent | 定义异步组件 | defineAsyncComponent(() => import('./Comp.vue')) |
h() | 创建虚拟节点 | h('div', { class: 'box' }, 'Content') |
<template>
<Suspense>
<template #default>
<AsyncComp />
</template>
<template #fallback>
<p>Loading...</p>
</template>
</Suspense>
</template>
<script>
import { defineAsyncComponent } from 'vue';
export default {
components: {
AsyncComp: defineAsyncComponent(() => import('./AsyncComp.vue'))
}
};
</script>
- 优先 Composition API:更灵活,支持 TypeScript。
- 结合工具:如 Vite 和 Vue DevTools,提升开发效率。
- 参考文档:查阅 Vue 3 官方文档 获取最新信息。
本速查表涵盖了 Vue 3 的核心 API、指令和工具,为你在开发中提供快速参考。无论是新手还是进阶开发者,都可以通过这些示例快速上手并应用到项目中。下一节将提供更多实用资源,继续丰富你的工具箱!