一、Vue.js 是什么
Vue.js 是一款用于构建用户界面的渐进式 JavaScript 框架。它的核心库只关注视图层,易于上手,同时配合生态工具可以构建复杂的单页应用。
Vue 3 相比 Vue 2 的主要改进:
- Composition API:更灵活的代码组织方式
- 更好的 TypeScript 支持
- 更小的包体积、更快的渲染性能
- Teleport、Suspense 等新内置组件
二、创建 Vue 应用
// 方式一:CDN 引入(快速体验)
// <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
// 方式二:Vite 脚手架创建项目(推荐)
// npm create vue@latest
// 入口文件 main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
三、响应式基础
import { ref, reactive, computed, watch } from 'vue'
// ref — 包装基本类型
const count = ref(0)
count.value++ // 修改需 .value
// reactive — 包装对象
const state = reactive({
name: 'Vue',
version: 3
})
// computed — 计算属性(缓存)
const double = computed(() => count.value * 2)
// watch — 监听变化
watch(count, (newVal, oldVal) => {
console.log(`count 从 ${oldVal} 变为 ${newVal}`)
})
四、常用指令
| 指令 | 作用 | 示例 |
|---|---|---|
| v-bind | 动态绑定属性 | :href="url" |
| v-model | 双向数据绑定 | <input v-model="text"> |
| v-if / v-else | 条件渲染(销毁/重建) | v-if="isShow" |
| v-show | 条件显示(display切换) | v-show="isShow" |
| v-for | 列表渲染 | v-for="item in list" |
| v-on | 事件绑定 | @click="handleClick" |
五、组件化开发
<!-- 父组件 -->
<template>
<Child :msg="message" @update="handleUpdate" />
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const message = ref('Hello')
const handleUpdate = (val) => { message.value = val }
</script>
<!-- 子组件 (Child.vue) -->
<script setup>
const props = defineProps({ msg: String })
const emit = defineEmits(['update'])
</script>
<template>
<div>{{ msg }}</div>
<button @click="emit('update', 'Updated')">更新</button>
</template>
六、生命周期钩子
| Vue 3 钩子 | Vue 2 对应 | 时机 |
|---|---|---|
| setup() | beforeCreate + created | 组件初始化 |
| onBeforeMount | beforeMount | 挂载前 |
| onMounted | mounted | DOM 挂载完成 |
| onBeforeUpdate | beforeUpdate | 数据更新前 |
| onUpdated | updated | DOM 更新后 |
| onBeforeUnmount | beforeDestroy | 卸载前 |
| onUnmounted | destroyed | 卸载后 |
七、总结
Vue 3 的 Composition API 让代码组织更加灵活,TypeScript 支持也让大型项目更加健壮。建议从官方文档和实战项目入手,循序渐进。