vue逻辑实现怎么实现
Vue 逻辑实现方法
Vue 的逻辑实现主要通过选项式 API(Options API)或组合式 API(Composition API)完成,核心围绕数据驱动、响应式系统和生命周期钩子展开。
选项式 API(Options API)
通过定义 data、methods、computed 等选项组织逻辑:
export default {
data() {
return { count: 0 };
},
methods: {
increment() {
this.count++;
}
},
computed: {
doubleCount() {
return this.count * 2;
}
}
};
组合式 API(Composition API)
使用 setup() 函数或 <script setup> 语法糖,逻辑通过函数组合实现:

import { ref, computed } from 'vue';
export default {
setup() {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
return { count, doubleCount, increment };
}
};
或使用 <script setup>:
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
function increment() {
count.value++;
}
</script>
响应式数据管理
ref: 用于基本类型或对象引用,通过.value访问。reactive: 仅用于对象,直接访问属性。computed: 派生状态,自动追踪依赖。watch: 监听数据变化执行副作用。
const state = reactive({ items: [] });
watch(() => state.items, (newVal) => {
console.log('Items changed:', newVal);
});
生命周期钩子
组合式 API 中通过 onMounted 等函数注册生命周期:

import { onMounted } from 'vue';
onMounted(() => {
console.log('Component mounted');
});
逻辑复用
使用 自定义 Hook 封装可复用逻辑:
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
function increment() {
count.value++;
}
return { count, increment };
}
组件中调用:
import { useCounter } from './useCounter';
const { count, increment } = useCounter();
事件与组件通信
$emit: 子组件触发父组件事件。v-model: 双向绑定语法糖。- Provide/Inject: 跨层级数据传递。
// 子组件
const emit = defineEmits(['update']);
function handleClick() {
emit('update', newValue);
}
// 父组件
<ChildComponent @update="handleUpdate" />
状态管理
复杂场景可使用 Pinia 或 Vuex:
// Pinia 示例
import { defineStore } from 'pinia';
export const useStore = defineStore('main', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++;
}
}
});
性能优化
v-ifvsv-show: 按需选择渲染方式。keep-alive: 缓存组件实例。- 异步组件: 延迟加载非关键组件。
const AsyncComponent = defineAsyncComponent(() =>
import('./Component.vue')
);
注意事项
- 避免直接修改
props,使用emit或v-model。 - 组合式 API 中注意响应式数据解构(使用
toRefs)。 - 大型项目推荐使用 TypeScript 增强类型安全。






