当前位置: 首页 > news >正文

Vue3 全面学习指南 - 从入门到实战

1. Vue3 简介与优势

1.1 Vue3 新特性

Vue3 是 Vue.js 的最新主要版本,带来了多项重大改进:

  • 性能提升:重写虚拟 DOM,初始渲染速度提升 100%,更新速度提升 133%

  • Tree-shaking 支持:按需引入功能,减小打包体积

  • Composition API:更好的逻辑组织和代码复用

  • 更好的 TypeScript 支持

  • 新的响应式系统:使用 Proxy 替代 Object.defineProperty

1.2 环境要求

  • Node.js 14.0+

  • 现代浏览器支持

2. 项目创建与配置

2.1 使用 Vite 创建项目

# 使用 npm
npm create vue@latest# 或使用 yarn
yarn create vue# 或使用 pnpm
pnpm create vue

2.2 项目结构

my-vue-app/
├── public/
├── src/
│   ├── components/
│   ├── views/
│   ├── stores/
│   ├── router/
│   ├── App.vue
│   └── main.js
├── package.json
└── vite.config.js

3. Composition API

3.1 响应式基础

<template><div><p>{{ count }}</p><button @click="increment">增加</button><p>{{ user.name }}</p></div>
</template><script setup>
import { ref, reactive } from 'vue'// 基本类型使用 ref
const count = ref(0)// 对象使用 reactive
const user = reactive({name: '张三',age: 25
})const increment = () => {count.value++user.age++
}
</script>

3.2 计算属性与侦听器

<script setup>
import { ref, computed, watch } from 'vue'const price = ref(10)
const quantity = ref(2)// 计算属性
const total = computed(() => price.value * quantity.value)// 侦听器
watch(quantity, (newValue, oldValue) => {console.log(`数量从 ${oldValue} 变为 ${newValue}`)
})// 深度侦听
watch(() => user,(newValue) => {console.log('用户信息变化:', newValue)},{ deep: true }
)
</script>

4. 组件系统

4.1 组件基础

<!-- ChildComponent.vue -->
<template><div class="child"><h3>{{ title }}</h3><slot name="header"></slot><p>{{ content }}</p><slot></slot><slot name="footer" :text="footerText"></slot></div>
</template><script setup>
defineProps({title: String,content: {type: String,default: '默认内容'}
})const footerText = '这是底部内容'
</script>

4.2 组件通信

<!-- ParentComponent.vue -->
<template><ChildComponent:title="parentTitle":content="parentContent"@update="handleUpdate"><template #header><h2>自定义头部</h2></template><p>默认插槽内容</p><template #footer="{ text }"><p>{{ text }}</p></template></ChildComponent>
</template><script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'const parentTitle = ref('父组件标题')
const parentContent = ref('父组件内容')const handleUpdate = (data) => {console.log('接收到子组件数据:', data)
}
</script>

5. 生命周期

<script setup>
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated,onBeforeUnmount,onUnmounted
} from 'vue'onBeforeMount(() => {console.log('挂载前')
})onMounted(() => {console.log('挂载完成')// 在这里进行 DOM 操作或数据请求
})onBeforeUpdate(() => {console.log('更新前')
})onUpdated(() => {console.log('更新完成')
})onBeforeUnmount(() => {console.log('卸载前')
})onUnmounted(() => {console.log('卸载完成')
})
</script>

6. 路由管理 (Vue Router 4)

6.1 路由配置

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'const routes = [{path: '/',name: 'Home',component: () => import('../views/Home.vue')},{path: '/about',name: 'About',component: () => import('../views/About.vue'),meta: { requiresAuth: true }},{path: '/user/:id',name: 'User',component: () => import('../views/User.vue'),props: true}
]const router = createRouter({history: createWebHistory(),routes
})// 路由守卫
router.beforeEach((to, from, next) => {if (to.meta.requiresAuth && !isLoggedIn()) {next('/login')} else {next()}
})export default router

6.2 路由使用

<template><div><nav><router-link to="/">首页</router-link><router-link to="/about">关于</router-link></nav><router-view></router-view></div>
</template><script setup>
import { useRouter, useRoute } from 'vue-router'const router = useRouter()
const route = useRoute()const goToAbout = () => {router.push('/about')
}// 获取路由参数
const userId = route.params.id
</script>

7. 状态管理 (Pinia)

7.1 Store 定义

// stores/counter.js
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', {state: () => ({count: 0,name: '计数器'}),getters: {doubleCount: (state) => state.count * 2,doubleCountPlusOne() {return this.doubleCount + 1}},actions: {increment() {this.count++},async incrementAsync() {await new Promise(resolve => setTimeout(resolve, 1000))this.increment()}}
})

7.2 Store 使用

<template><div><p>{{ count }}</p><p>{{ doubleCount }}</p><button @click="increment">增加</button><button @click="incrementAsync">异步增加</button></div>
</template><script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'const counterStore = useCounterStore()// 使用 storeToRefs 保持响应式
const { count, doubleCount } = storeToRefs(counterStore)const { increment, incrementAsync } = counterStore
</script>

8. 高级特性

8.1 自定义指令

// directives/focus.js
export const vFocus = {mounted: (el) => {el.focus()},updated: (el, binding) => {if (binding.value) {el.focus()}}
}// 在组件中使用
<script setup>
import { vFocus } from '@/directives/focus'
</script><template><input v-focus="shouldFocus" />
</template>

8.2 插件开发

// plugins/i18n.js
export default {install: (app, options) => {app.config.globalProperties.$translate = (key) => {return key.split('.').reduce((o, i) => {if (o) return o[i]}, options)}app.provide('i18n', options)}
}

9. 最佳实践

9.1 代码组织

<script setup>
// 1. 导入
import { ref, computed, onMounted } from 'vue'// 2. 响应式数据
const count = ref(0)
const user = reactive({ name: '' })// 3. 计算属性
const doubleCount = computed(() => count.value * 2)// 4. 方法
const increment = () => count.value++// 5. 生命周期
onMounted(() => {// 初始化逻辑
})// 6. 监听器
watch(count, (newVal) => {console.log(newVal)
})
</script>

9.2 性能优化

  • 使用 v-once 静态内容

  • 合理使用 v-memo

  • 组件懒加载

  • 列表使用 key

10. TypeScript 支持

<template><div><p>{{ message }}</p><button @click="increment">{{ count }}</button></div>
</template><script setup lang="ts">
import { ref, computed } from 'vue'interface User {name: stringage: number
}// 类型推断
const count = ref<number>(0)
const user = ref<User>({ name: 'John', age: 25 })const message = computed(() => `Count: ${count.value}`)const increment = (): void => {count.value++
}
</script>

总结

Vue3 通过 Composition API 提供了更灵活的逻辑组织方式,配合更好的 TypeScript 支持和性能优化,使得开发体验更加优秀。建议从基础开始,逐步掌握各个模块,最终能够熟练运用 Vue3 进行项目开发。

希望这份笔记对您的学习有所帮助!

http://www.dtcms.com/a/546424.html

相关文章:

  • 等保测评取消打分,《网络安全等级测评报告模版(2025版)》重大变更,详细解读两细化、三变更、五新增
  • 响应式商场网站百度公司招聘信息
  • pytorch-数值微分
  • 网站赚钱方法花艺企业网站建设规划
  • 网站开发工具书营销型网站建设项目需求表
  • JAVA的项目复制
  • 关于架构设计的依赖关系
  • 网站优化费用报价明细唐山百度做网站多少钱
  • 旅游门户网站模板下载茂民网站建设
  • ​(吉林版)安全员C证模拟考试练习题与答案
  • 城乡住房建设网站介绍常见的网络营销方式
  • RAG与数据预测的结合应用(1) - 语义相似度的提升
  • 有模板了怎么建设网站哪家公司建设网站好
  • 36氪国外做网站青岛网站设计建议i青岛博采网络
  • 网站开发作业汕头专业网站建设流程
  • (华为欧拉系统)openEuler-22.03、openEuler-24.03安装-MySQL-8.0和MySQL-8.4
  • 就业创业网站建设长春做网站选长春万网
  • @Required注解有什么用?
  • ARM《7》_编译生成linux内核中的内核模块
  • STM32H743-ARM例程33-TOUCH
  • 大型网站开发团队网站更换模板
  • 网站建设规划ppt模板大名专业做网站
  • 重庆seo网站策划网站建设项目管理基本要求
  • GEO 优化赋能品牌推广,AI 时代的新玩法
  • Sui Stack 助力 AI 从“强大”走向“可信”
  • 营销型网站需要注意天河做网站企业
  • 建网站用哪个好网站建设经费预算策划书
  • 响应时间差 3 倍?华为云 Flexus 部署 DeepSeek+Dify 企业级 AI 性能深度测评
  • 手机网站建设价格明细表wordpress打字特效
  • 网站配色绿色全包圆装修公司