vue 实现手册
Vue 实现手册
基础项目搭建
使用 Vue CLI 快速初始化项目,确保已安装 Node.js 和 npm/yarn。
运行命令创建项目:
npm install -g @vue/cli
vue create my-project
cd my-project
npm run serve
核心语法
模板语法
通过双大括号插值绑定数据:
<div>{{ message }}</div>
使用指令如 v-bind 绑定属性:
<img v-bind:src="imageUrl">
响应式数据
在 data 中定义响应式变量:
data() {
return {
message: 'Hello Vue!'
}
}
组件开发
定义组件
单文件组件结构(.vue 文件):
<template>
<button @click="handleClick">{{ buttonText }}</button>
</template>
<script>
export default {
props: ['buttonText'],
methods: {
handleClick() {
this.$emit('button-click');
}
}
}
</script>
组件通信
父组件通过 props 传递数据:
<ChildComponent :data="parentData" />
子组件通过 $emit 触发事件:
this.$emit('update-data', newData);
状态管理(Vuex)
Store 配置
创建全局状态管理:
import Vuex from 'vuex';
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) {
state.count++;
}
}
});
组件中使用
通过 mapState 和 mapMutations 简化调用:
import { mapState, mapMutations } from 'vuex';
export default {
computed: mapState(['count']),
methods: mapMutations(['increment'])
};
路由管理(Vue Router)
路由配置
定义路由表:
import VueRouter from 'vue-router';
import Home from './views/Home.vue';
const routes = [
{ path: '/', component: Home }
];
const router = new VueRouter({ routes });
导航控制
通过 <router-link> 和编程式导航:
<router-link to="/about">About</router-link>
this.$router.push('/about');
进阶技巧
自定义指令
实现全局指令:
Vue.directive('focus', {
inserted(el) {
el.focus();
}
});
混入(Mixins)
复用逻辑:
const myMixin = {
created() {
console.log('Mixin hook');
}
};
export default {
mixins: [myMixin]
};
性能优化
懒加载路由
动态导入组件提升首屏速度:
const About = () => import('./views/About.vue');
计算属性缓存
替代复杂模板逻辑:
computed: {
filteredList() {
return this.list.filter(item => item.active);
}
}
测试与调试
单元测试
使用 Jest 测试组件:
import { shallowMount } from '@vue/test-utils';
import MyComponent from './MyComponent.vue';
test('renders message', () => {
const wrapper = shallowMount(MyComponent);
expect(wrapper.text()).toContain('Hello');
});
DevTools 集成
安装 Vue DevTools 浏览器扩展,实时检查组件树和状态。







