vue功能实现
Vue 功能实现的核心方法
组件化开发
Vue 的核心思想是组件化,通过单文件组件(.vue文件)将模板、逻辑和样式封装在一起。组件通过 props 接收父组件数据,通过 $emit 触发事件实现父子通信。
<template>
<button @click="handleClick">{{ buttonText }}</button>
</template>
<script>
export default {
props: ['buttonText'],
methods: {
handleClick() {
this.$emit('button-clicked');
}
}
}
</script>
响应式数据绑定
Vue 使用 data() 返回响应式对象,数据变化自动更新视图。计算属性 (computed) 和侦听器 (watch) 用于处理复杂逻辑。
data() {
return {
count: 0
}
},
computed: {
doubledCount() {
return this.count * 2;
}
},
watch: {
count(newVal) {
console.log(`Count changed to ${newVal}`);
}
}
生命周期钩子
Vue 组件提供从创建到销毁的钩子函数,如 created、mounted、updated 等,用于在特定阶段执行代码。
created() {
console.log('Component created');
},
mounted() {
this.fetchData();
}
状态管理 (Vuex/Pinia)
复杂应用可使用 Vuex 或 Pinia 管理全局状态。Vuex 的核心概念包括 state、mutations、actions 和 getters。

// Vuex 示例
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) {
state.count++;
}
}
});
路由管理 (Vue Router)
Vue Router 实现单页应用导航,通过路由配置映射组件到 URL。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({ routes });
指令系统
Vue 提供内置指令如 v-if、v-for、v-bind、v-model 等,扩展模板功能。
<div v-if="showElement">显示内容</div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<input v-model="username">
插件系统
通过 Vue.use() 安装插件,扩展 Vue 功能。常见插件如 vue-router、vue-i18n 等。

Vue.use(VueRouter);
Vue.use(VueI18n);
组合式 API (Vue 3)
Vue 3 引入 setup() 函数和组合式 API,提供更灵活的代码组织方式。
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const doubled = computed(() => count.value * 2);
</script>
服务端渲染 (Nuxt.js)
使用 Nuxt.js 框架实现服务端渲染,改善 SEO 和首屏加载性能。
// nuxt.config.js
export default {
modules: ['@nuxtjs/axios'],
axios: {
baseURL: 'https://api.example.com'
}
}
性能优化
关键优化手段包括:懒加载路由组件、按需引入第三方库、使用 v-once 和 v-memo 指令、合理使用 keep-alive。
// 路由懒加载
const UserDetails = () => import('./views/UserDetails.vue');






