Vue.js知识总结
以下是 Vue.js 的重要知识点及代码示例:
1. 响应式数据
Vue 通过 ref
和 reactive
实现数据响应式。
<script setup>
import { ref, reactive } from 'vue';
const count = ref(0); // 基本类型用 ref
const user = reactive({ name: 'Alice', age: 25 }); // 对象用 reactive
function increment() {
count.value++; // ref 需要 .value 访问
user.age++;
}
</script>
<template>
<button @click="increment">{{ count }}</button>
<p>{{ user.name }} - {{ user.age }}</p>
</template>
2. 模板语法
- 插值:
{{ }}
- 指令:
v-bind
,v-model
,v-if
,v-for
等
<template>
<!-- 绑定属性 -->
<a :href="url">Link</a>
<!-- 双向绑定 -->
<input v-model="message">
<!-- 条件渲染 -->
<div v-if="isVisible">显示内容</div>
<!-- 列表渲染 -->
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
3. 组件通信
-
Props(父传子):
<!-- 父组件 --> <ChildComponent :message="parentMsg" /> <!-- 子组件 --> <script setup> const props = defineProps({ message: String }); </script>
-
自定义事件(子传父):
<!-- 子组件 --> <button @click="$emit('update', data)">提交</button> <!-- 父组件 --> <ChildComponent @update="handleUpdate" />
4. 计算属性 & 侦听器
-
计算属性:缓存结果,依赖变化时重新计算
<script setup> import { computed } from 'vue'; const fullName = computed(() => `${firstName} ${lastName}`); </script>
-
侦听器:监听数据变化执行副作用
<script setup> import { watch } from 'vue'; watch(count, (newVal, oldVal) => { console.log(`Count changed from ${oldVal} to ${newVal}`); }); </script>
5. 生命周期钩子
常用钩子:onMounted
, onUpdated
, onUnmounted
(Vue 3 组合式 API)
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
console.log('组件挂载完成');
fetchData(); // 初始化数据
});
</script>
6. Vue Router
-
路由配置:
// router.js const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ];
-
导航守卫:
router.beforeEach((to, from, next) => { if (to.meta.requiresAuth && !isLoggedIn) next('/login'); else next(); });
7. Vuex(状态管理)
-
核心概念:
// store.js const store = createStore({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }, actions: { asyncIncrement({ commit }) { setTimeout(() => commit('increment'), 1000); } } });
-
组件中使用:
<script setup> import { useStore } from 'vuex'; const store = useStore(); const count = computed(() => store.state.count); </script>
8. 组合式 API(Composition API)
Vue 3 的特性,替代 Options API:
<script setup>
import { ref, onMounted } from 'vue';
// 逻辑复用示例:鼠标跟踪
function useMouse() {
const x = ref(0);
const y = ref(0);
onMounted(() => {
window.addEventListener('mousemove', (e) => {
x.value = e.clientX;
y.value = e.clientY;
});
});
return { x, y };
}
const { x, y } = useMouse();
</script>
<template>鼠标位置:{{ x }}, {{ y }}</template>
总结
以上是 Vue 的核心知识点,实际开发中还可能涉及:
- 自定义指令
- 过渡动画(
<transition>
) - 服务端渲染(SSR)
- 性能优化(如
v-once
、keep-alive
) - TypeScript 集成等
可以根据项目需求进一步深入!