Vue 3 实战指南
Vue 3 是当前流行的前端框架之一,具有更好的性能、更小的体积和更优秀的组合式API。下面我将介绍Vue 3的核心概念和实战技巧。
1. 项目创建与基础配置
创建Vue 3项目
npm init vue@latest my-vue-app
# 或
yarn create vue my-vue-app
主要目录结构
my-vue-app/
├── public/ # 静态资源
├── src/
│ ├── assets/ # 静态资源
│ ├── components/ # 组件
│ ├── composables/ # 组合式函数
│ ├── router/ # 路由配置
│ ├── stores/ # Pinia状态管理
│ ├── views/ # 页面级组件
│ ├── App.vue # 根组件
│ └── main.js # 应用入口
├── vite.config.js # Vite配置
└── package.json
2. 组合式API (Composition API)
基本使用
<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
// 响应式数据
const count = ref(0)
const state = reactive({
name: 'Vue 3',
version: '3.2.0'
})
// 计算属性
const versionInfo = computed(() => {
return `${state.name} ${state.version}`
})
// 方法
function increment() {
count.value++
}
// 生命周期钩子
onMounted(() => {
console.log('组件已挂载')
})
// 侦听器
watch(count, (newValue, oldValue) => {
console.log(`count从${oldValue}变为${newValue}`)
})
</script>
<template>
<div>
<h1>{
{ versionInfo }}</h1>
<p>Count: {
{ count }}</p>
<button @click="increment">增加</button>
</div>
</template>
组合式函数 (Composables)
创建可复用的逻辑:
// src/composables/useCounter.js
import {
ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
function increment() {
count.value++
}
function decrement() {
count.value--
}
function reset() {
count.value = initialValue
}
return {
count,
increment,
decrement,
reset
}
}
使用组合式函数:
<script setup>
import { useCounter } from '@/composables/useCounter'
const { count, increment } = useCounter(10)
</script>