vue各种功能实现
Vue 基础功能实现
数据绑定
使用 v-model 实现双向数据绑定,适用于表单输入、复选框等场景:
<input v-model="message">
<p>{{ message }}</p>
数据通过 data() 定义:
data() {
return {
message: 'Hello Vue!'
}
}
条件渲染v-if 和 v-show 控制元素显示:
<div v-if="isVisible">显示内容</div>
<div v-show="isActive">动态显示</div>
列表渲染v-for 渲染数组或对象:
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.name }}
</li>
Vue 组件通信
Props 传递数据
父组件通过属性传递数据:
<ChildComponent :title="parentTitle" />
子组件通过 props 接收:
props: ['title']
自定义事件
子组件通过 $emit 触发事件:
this.$emit('update', newValue)
父组件监听事件:
<ChildComponent @update="handleUpdate" />
Vuex 状态管理
定义 store:
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) {
state.count++
}
}
})
组件中调用:
this.$store.commit('increment')
Vue 路由功能
路由配置
通过 Vue Router 定义路径:
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]
导航守卫
全局前置守卫:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) next('/login')
else next()
})
Vue 高级特性
动态组件
通过 :is 切换组件:
<component :is="currentComponent"></component>
插槽(Slots)
父组件传递模板片段:
<ChildComponent>
<template v-slot:header>
<h1>标题内容</h1>
</template>
</ChildComponent>
混入(Mixins)
复用逻辑:
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('Mixin loaded')
}
}
}
Vue 性能优化
异步组件
按需加载组件:
const AsyncComponent = () => ({
component: import('./AsyncComponent.vue'),
loading: LoadingComponent,
error: ErrorComponent
})
计算属性缓存
使用 computed 替代复杂表达式:
computed: {
filteredList() {
return this.list.filter(item => item.active)
}
}
Keep-alive
缓存组件状态:
<keep-alive>
<component :is="currentTab"></component>
</keep-alive>
Vue 3 组合式 API
setup 函数
替代 data 和 methods:
setup() {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
}
生命周期钩子
使用 onMounted 等函数:

import { onMounted } from 'vue'
setup() {
onMounted(() => {
console.log('组件已挂载')
})
}






