Vue学习指南
来源
原始文档: Vue学习指南.md
核心内容
Vue.js 前端框架学习路径和核心概念。
创建项目
# Vue CLI
npm install -g @vue/cli
vue create my-project
# Vite (推荐)
npm create vue@latest
# 或
npm init vue@latest
核心概念
模板语法
<template>
<!-- 文本插值 -->
<span>{{ message }}</span>
<!-- 指令 -->
<p v-if="seen">Now you see me</p>
<a v-bind:href="url">Link</a>
<button v-on:click="doSomething">Click</button>
<input v-model="inputValue" />
<!-- 列表渲染 -->
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</template>
响应式数据
<script setup>
import { ref, reactive, computed } from 'vue'
// ref - 基本类型
const count = ref(0)
count.value++
// reactive - 对象
const state = reactive({ count: 0 })
state.count++
// computed
const doubleCount = computed(() => count.value * 2)
</script>
生命周期钩子
<script setup>
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log('组件已挂载')
})
onUnmounted(() => {
console.log('组件已卸载')
})
</script>
组件通信
<!-- 父组件 -->
<Child :msg="parentMsg" @update="handleUpdate" />
<!-- 子组件 -->
<script setup>
defineProps(['msg'])
const emit = defineEmits(['update'])
const sendToParent = () => {
emit('update', 'new value')
}
</script>
路由
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/user/:id', component: User }
]
})
状态管理 (Pinia)
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})
关键要点
- Vue 3 使用 Composition API 和