Vue API Beginner's Guide: Core Concepts, Practical Cases, and Best Practices
This comprehensive tutorial introduces Vue.js core APIs—including component creation, reactive data handling, lifecycle hooks, routing, and state management—illustrates their use through e‑commerce cart and social feed examples, and provides performance tips and common pitfalls for front‑end developers.
1. Vue API Introduction
Vue.js is a popular JavaScript framework for building user interfaces using standard HTML, CSS, and JavaScript. Its declarative, component‑based model boosts development efficiency for both small projects and large applications.
The Vue API is the toolbox that enables developers to create components, manage data, handle user interactions, and optimize performance, making it essential for any front‑end engineer.
2. Core Vue APIs Focused on Business Development
2.1 Component Foundations
Vue provides APIs for defining and registering components. In Vue 2, Vue.component('my-button', { ... }) registers a global component; in Vue 3, the preferred approach is using defineComponent with the setup function.
Vue.component('my-button', {
template: '<button @click="handleClick">{{ buttonText }}</button>',
data() { return { buttonText: '点击我' }; },
methods: { handleClick() { alert('按钮被点击了'); } }
}); import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const buttonText = ref('点击我');
const handleClick = () => { alert('按钮被点击了'); };
return { buttonText, handleClick };
},
template: '<button @click="handleClick">{{ buttonText }}</button>'
});Vue 2 also offers Vue.extend for creating component constructors, which is less common in Vue 3 but useful for understanding component inheritance.
const ExtendedComponent = Vue.extend({
template: '<div><p>{{ message }}</p><input v-model="message" /></div>',
data() { return { message: '初始消息' }; }
});
new ExtendedComponent().$mount('#app');2.2 Reactive Data Magic
Vue 3 introduces ref for primitive reactive values and reactive for objects/arrays. Changes automatically update the DOM.
import { ref } from 'vue';
const count = ref(0);
function increment() { count.value++; } import { reactive } from 'vue';
const state = reactive({
todos: [
{ text: '学习 Vue', done: false },
{ text: '完成项目', done: false }
]
});
function toggleTodo(index) { state.todos[index].done = !state.todos[index].done; }The watch API monitors changes, while watchEffect automatically tracks dependencies.
import { ref, watch } from 'vue';
const name = ref('');
watch(name, (newValue, oldValue) => {
console.log(`名字从 ${oldValue} 变为了 ${newValue}`);
}); import { ref, watchEffect } from 'vue';
const count = ref(0);
watchEffect(() => { console.log(`当前计数:${count.value}`); });2.3 Lifecycle Hooks
Vue 2 lifecycle hooks include created , mounted , updated , and destroyed . Vue 3 uses the composition‑API equivalents such as onMounted , onBeforeUnmount , etc.
export default {
created() { this.fetchData(); },
methods: { fetchData() { /* request data */ } }
}; import { onMounted, onBeforeUnmount, ref } from 'vue';
const count = ref(0);
onMounted(() => { console.log('组件挂载完成'); });
onBeforeUnmount(() => { console.log('组件即将卸载'); });2.4 Router Navigation API
Vue Router manages SPA navigation. Create a router with createRouter and define routes, then use router.push or router.replace for programmatic navigation.
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
}); import { useRouter } from 'vue-router';
export default {
setup() {
const router = useRouter();
const goToAbout = () => { router.push('/about'); };
return { goToAbout };
}
};2.5 State Management with Vuex
Vuex provides a centralized store with state , mutations , actions , and getters . Mutations synchronously modify state, while actions handle asynchronous logic.
const store = new Vuex.Store({
state: { count: 0 },
mutations: { increment(state) { state.count++; } }
}); const store = new Vuex.Store({
state: { cart: { items: [] } },
mutations: {
updateCartItemQuantity(state, { id, quantity }) {
const item = state.cart.items.find(i => i.id === id);
if (item) item.quantity = quantity;
},
updateCartItemSelected(state, { id, selected }) {
const item = state.cart.items.find(i => i.id === id);
if (item) item.selected = selected;
}
},
actions: {
loadCartData({ commit }) {
return axios.get('/api/cart').then(res => { commit('setCartItems', res.data); });
}
}
});3. Practical Cases
3.1 E‑Commerce Shopping Cart
A cart page uses component APIs to render a list of CartItem components, communicates quantity and selection changes via custom events, and updates the Vuex store.
<template>
<div>
<CartItem v-for="item in cartItems" :key="item.id" :item="item"
@update-quantity="updateQuantity" @update-selected="updateSelected" />
</div>
</template>
<script setup>
import CartItem from './CartItem.vue';
import { ref } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const cartItems = ref(store.state.cart.items);
const updateQuantity = (id, qty) => { store.commit('updateCartItemQuantity', { id, quantity: qty }); };
const updateSelected = (id, sel) => { store.commit('updateCartItemSelected', { id, selected: sel }); };
</script>3.2 Social Feed Page
The feed list renders FeedItem components, handling likes and comments through Vuex mutations.
<template>
<div>
<FeedItem v-for="feed in feedList" :key="feed.id" :feed="feed"
@like="handleLike" @comment="handleComment" />
</div>
</template>
<script setup>
import FeedItem from './FeedItem.vue';
import { ref } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const feedList = ref(store.state.feed.list);
const handleLike = id => { store.commit('likeFeed', id); };
const handleComment = (id, comment) => { store.commit('addComment', { id, comment }); };
</script>4. Tips and Pitfalls
When calling multiple APIs, use Promise.all for parallel requests unless there are dependencies. Optimize performance by limiting reactive data to frequently changing parts and leveraging computed caching.
import axios from 'axios';
Promise.all([axios.get('/api/user'), axios.get('/api/products')])
.then(([u, p]) => { /* handle data */ })
.catch(err => console.error(err));Be careful with deep watchers ( { deep: true } ) as they can incur overhead. When using provide/inject , ensure provided data is reactive if you need updates.
export default {
setup() {
const sharedData = reactive({ message: '初始消息' });
provide('shared', sharedData);
return { sharedData };
}
};
// child
export default {
setup() {
const shared = inject('shared');
return { shared };
}
};5. Conclusion and Outlook
The tutorial demonstrates how Vue’s component system, reactive data model, lifecycle hooks, routing, and Vuex state management together empower developers to build robust, high‑performance front‑end applications. Continued learning of emerging Vue features will further enhance developers’ ability to create sophisticated web experiences.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.