vue各种功能实现
Vue 基础功能实现
数据绑定与响应式更新
使用 v-model 实现表单元素与数据的双向绑定,数据变更自动更新视图。
示例:
<input v-model="message">
<p>{{ message }}</p>
data() {
return { message: '' }
}
条件渲染
通过 v-if、v-else 或 v-show 控制元素显示/隐藏。
<div v-if="isVisible">显示内容</div>
<div v-else>备选内容</div>
列表渲染
使用 v-for 渲染数组或对象,需配合 :key 提升性能。
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.name }}
</li>
Vue 组件通信
Props 父传子
父组件通过属性传递数据,子组件用 props 接收。
// 父组件
<ChildComponent :title="parentTitle" />
// 子组件
props: ['title']
$emit 子传父
子组件通过事件触发向父组件传递数据。
// 子组件
this.$emit('update', newValue)
// 父组件
<ChildComponent @update="handleUpdate" />
Event Bus 跨组件通信
创建全局事件总线实现任意组件间通信。
// main.js
export const eventBus = new Vue()
// 组件A
eventBus.$emit('eventName', data)
// 组件B
eventBus.$on('eventName', (data) => { ... })
Vue 状态管理(Vuex)
State 与 Getters
定义全局状态和计算属性。
state: { count: 0 },
getters: {
doubleCount: state => state.count * 2
}
Mutations 同步修改
通过提交 mutation 更改状态。
mutations: {
increment(state, payload) {
state.count += payload
}
}
// 调用
this.$store.commit('increment', 10)
Actions 异步操作
处理异步逻辑后提交 mutation。
actions: {
asyncIncrement({ commit }, delay) {
setTimeout(() => commit('increment', 1), delay)
}
}
// 调用
this.$store.dispatch('asyncIncrement', 1000)
Vue 路由(Vue Router)
路由配置与导航
定义路由路径和组件映射,使用 <router-link> 导航。
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
// 导航
<router-link to="/about">关于</router-link>
动态路由与参数
通过冒号标记动态路径参数。
{ path: '/user/:id', component: User }
// 获取参数
this.$route.params.id
导航守卫
控制路由跳转前后的逻辑。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn) next('/login')
else next()
})
Vue 进阶功能
自定义指令
实现原生 DOM 操作的封装。
Vue.directive('focus', {
inserted(el) {
el.focus()
}
})
// 使用
<input v-focus>
混入(Mixins)
复用组件选项逻辑。
const myMixin = {
created() { console.log('混入钩子') }
}
// 使用
mixins: [myMixin]
插件开发
扩展 Vue 的全局功能。
const MyPlugin = {
install(Vue) {
Vue.prototype.$myMethod = () => { ... }
}
}
// 使用
Vue.use(MyPlugin)
性能优化技巧
懒加载路由组件
通过动态导入减少初始加载体积。
const Home = () => import('./Home.vue')
Keep-alive 缓存组件
保留组件状态避免重复渲染。
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
虚拟滚动优化长列表
使用 vue-virtual-scroller 等库提升渲染性能。
<RecycleScroller :items="largeList" :item-size="50">
<template v-slot="{ item }">
<div>{{ item.content }}</div>
</template>
</RecycleScroller>






