vue常用功能实现
Vue 常用功能实现
数据绑定与响应式更新
使用 v-model 实现表单元素与数据的双向绑定:
<input v-model="message" placeholder="输入内容">
<p>{{ message }}</p>
在 Vue 实例中定义数据:
data() {
return {
message: ''
}
}
条件渲染
通过 v-if 或 v-show 控制元素显示:
<div v-if="isVisible">条件为真时显示</div>
<div v-show="isActive">通过CSS切换显示</div>
列表渲染
使用 v-for 渲染数组或对象:
<ul>
<li v-for="(item, index) in items" :key="index">{{ item.name }}</li>
</ul>
数据定义:
data() {
return {
items: [{ name: 'A' }, { name: 'B' }]
}
}
事件处理
通过 v-on(或 @ 简写)绑定事件:
<button @click="handleClick">点击触发</button>
方法定义:
methods: {
handleClick() {
alert('事件触发');
}
}
计算属性与侦听器
计算属性缓存结果,适合复杂逻辑:
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}
侦听器响应数据变化:

watch: {
message(newVal, oldVal) {
console.log(`数据从 ${oldVal} 变为 ${newVal}`);
}
}
组件通信
父组件通过 props 传递数据:
<child-component :title="parentTitle"></child-component>
子组件接收:
props: ['title']
子组件通过 $emit 触发父组件事件:
this.$emit('update', newData);
动态组件
通过 <component> 切换组件:
<component :is="currentComponent"></component>
路由管理(Vue Router)
定义路由并渲染视图:

const routes = [{ path: '/home', component: Home }];
const router = createRouter({ history: createWebHistory(), routes });
在模板中使用:
<router-link to="/home">首页</router-link>
<router-view></router-view>
状态管理(Vuex/Pinia)
以 Pinia 为例定义 store:
export const useStore = defineStore('main', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++;
}
}
});
组件中使用:
const store = useStore();
store.increment();
生命周期钩子
常用钩子如 mounted 和 updated:
mounted() {
console.log('组件挂载完成');
}
自定义指令
全局注册指令:
app.directive('focus', {
mounted(el) {
el.focus();
}
});
使用指令:
<input v-focus>






