利用vue 实现
以下是利用 Vue 实现常见功能的几种方法,基于 Vue 3 的 Composition API 和选项式 API 分别说明:
响应式数据绑定
使用 ref 或 reactive 创建响应式数据:
import { ref, reactive } from 'vue';
// Composition API
const count = ref(0);
const state = reactive({ name: 'Vue' });
// 选项式 API
export default {
data() {
return {
count: 0,
state: { name: 'Vue' }
}
}
}
条件渲染
通过 v-if 和 v-show 控制元素显示:
<template>
<div v-if="isVisible">显示内容</div>
<div v-show="isActive">总是渲染但控制CSS</div>
</template>
<script setup>
const isVisible = ref(true);
const isActive = ref(false);
</script>
列表渲染
使用 v-for 渲染数组:

<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.text }}
</li>
</ul>
</template>
<script setup>
const items = ref([
{ text: '项目1' },
{ text: '项目2' }
]);
</script>
事件处理
通过 v-on 或 @ 绑定事件:
<template>
<button @click="handleClick">点击</button>
</template>
<script setup>
const handleClick = () => {
console.log('点击事件');
};
</script>
表单双向绑定
使用 v-model 实现双向绑定:
<template>
<input v-model="message" placeholder="输入内容">
<p>{{ message }}</p>
</template>
<script setup>
const message = ref('');
</script>
组件通信
父子组件通信示例:

<!-- 父组件 -->
<template>
<ChildComponent :title="parentTitle" @update="handleUpdate"/>
</template>
<script setup>
const parentTitle = ref('父组件标题');
const handleUpdate = (value) => {
console.log('子组件传递的值:', value);
};
</script>
<!-- 子组件 -->
<template>
<div>{{ title }}</div>
<button @click="$emit('update', '新值')">触发事件</button>
</template>
<script setup>
defineProps(['title']);
defineEmits(['update']);
</script>
生命周期钩子
Composition API 使用生命周期:
import { onMounted, onUpdated } from 'vue';
onMounted(() => {
console.log('组件挂载完成');
});
onUpdated(() => {
console.log('组件更新完成');
});
状态管理(Pinia)
创建和使用 store:
// store/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++;
}
}
});
// 组件中使用
import { useCounterStore } from '@/store/counter';
const counter = useCounterStore();
counter.increment();
路由管理(Vue Router)
基本路由配置:
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
});
// 组件内导航
import { useRouter } from 'vue-router';
const router = useRouter();
router.push('/about');
以上代码示例涵盖了 Vue 开发中的核心功能,可根据实际需求组合使用。Vue 3 的 Composition API 提供了更灵活的代码组织方式,而选项式 API 更适合简单场景。






