vue各种功能实现
Vue 核心功能实现
双向数据绑定
通过 v-model 指令实现表单元素与数据的双向同步。例如文本输入框:
<input v-model="message">
<p>{{ message }}</p>
数据变化会自动更新视图,用户输入也会同步到数据。
条件渲染
使用 v-if 和 v-show 控制元素显示:
<div v-if="isVisible">仅当isVisible为true时渲染</div>
<div v-show="hasData">通过CSS切换显示</div>
v-if 是动态添加/移除DOM,v-show 仅切换 display 属性。
列表渲染与事件处理
动态列表v-for 指令渲染数组或对象:
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.name }}
</li>
:key 是必须的,用于高效更新虚拟DOM。
事件绑定
通过 v-on(简写 @)监听事件:
<button @click="handleClick">点击</button>
<button @click.prevent="submit">阻止默认事件</button>
修饰符如 .prevent 可替代 event.preventDefault()。
组件化开发
组件定义
单文件组件(SFC)结构:
<template>
<div>{{ title }}</div>
</template>
<script>
export default {
props: ['title'],
data() { return { localData: 1 } }
}
</script>
组件通信
- 父传子:通过
props<ChildComponent :propName="parentData" /> - 子传父:通过
$emitthis.$emit('event-name', payload)
状态管理(Vuex)
核心概念
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++ }
},
actions: {
asyncIncrement({ commit }) {
setTimeout(() => commit('increment'), 1000)
}
}
})
组件中通过 this.$store.commit('increment') 触发变更。
路由管理(Vue Router)
基础配置
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = new VueRouter({ routes })
导航方式:
<router-link to="/about">跳转</router-link>
或编程式导航:
this.$router.push('/about')
高级特性
自定义指令
全局注册指令:
Vue.directive('focus', {
inserted(el) { el.focus() }
})
使用方式:
<input v-focus>
混入(Mixins)
复用逻辑:
const myMixin = {
created() { console.log('混入生命周期') }
}
new Vue({ mixins: [myMixin] })
性能优化
异步组件
按需加载组件:
const AsyncComponent = () => ({
component: import('./AsyncComponent.vue'),
loading: LoadingComponent
})
Keep-alive
缓存组件状态:

<keep-alive>
<component :is="currentTab"></component>
</keep-alive>






