Vue3 手绘风学习笔记:从 Composition API 到快速上手

5 阅读3分钟

Vue3 手绘风学习笔记:从 Composition API 到快速上手

✏️ Vue3 手绘风学习笔记 🎨

主打一个随手记、轻松学,核心知识点+极简示例,新手友好~

📝 前言

Vue3 是目前 Vue 的主流版本,相比 Vue2 重构了核心代码,更轻量、更灵活,还支持 TypeScript 友好开发,最香的是 Composition API(组合式API),终于不用再被选项式API的this绕晕啦~

🚀 核心特性(敲黑板!)

1. 🌟 Composition API(组合式API)

最核心的升级!把零散的代码按功能逻辑聚合,不再局限于 data/methods/watch 这些选项,复用性拉满~

<template>
  <div>计数:{{ count }}</div>
  <button @click="add">点我+1</button>
</template>

<script setup>
// ✨ 直接写,不用export default,setup语法糖yyds
import { ref } from 'vue'

// 响应式数据(简单类型用ref)
const count = ref(0)

// 方法直接定义
const add = () => {
  count.value++ // ref要加.value,模板里不用
}
</script>

2. 🛠️ 响应式原理升级

Vue2 用 Object.defineProperty,只能监听对象属性;Vue3 用 Proxy,能监听整个对象,还支持数组、Map/Set 啦~

<script setup>
import { reactive } from 'vue'

// 复杂类型用reactive
const user = reactive({
  name: '手绘君',
  hobbies: ['摸鱼', '写Vue'] // 数组响应式直接用,不用再hack啦
})

// 直接改数组,响应式生效!
const addHobby = () => {
  user.hobbies.push('学Vue3')
}
</script>

3. 🧩 组件相关升级

(1)组件传值更简洁
<!-- 子组件 Child.vue -->
<script setup>
// ✨ 直接defineProps,不用写props选项
const props = defineProps({
  msg: {
    type: String,
    default: '默认手绘消息'
  }
})

// 子传父:defineEmits
const emit = defineEmits(['changeMsg'])
const sendMsg = () => {
  emit('changeMsg', '来自子组件的手绘消息')
}
</script>
(2)Teleport(瞬移组件)

把组件渲染到任意DOM节点,弹框/遮罩再也不用被父组件样式限制啦~

<template>
  <button @click="showModal = true">打开弹窗</button>
  <!-- 📍 瞬移到body下 -->
  <Teleport to="body">
    <div v-if="showModal" class="modal">
      我是瞬移的弹窗~
      <button @click="showModal = false">关闭</button>
    </div>
  </Teleport>
</template>

<script setup>
import { ref } from 'vue'
const showModal = ref(false)
</script>

4. ⚡ 更轻量、更快

  • 体积更小:按需引入,打包后体积比Vue2少约40%
  • 编译更快:静态节点提升、PatchFlag标记动态节点,更新DOM更精准

📦 快速上手(极简版)

1. 创建Vue3项目

# 先装脚手架
npm install -g @vue/cli
# 创建项目(选Vue3)
vue create vue3-handnote
# 或用vite(更快!)
npm create vite@latest vue3-handnote -- --template vue

2. 最简Vue3组件

<script setup>
// setup语法糖是Vue3的标配,不用写setup函数
import { ref, reactive } from 'vue'

// 响应式数据
const title = ref('Vue3手绘笔记')
const info = reactive({
  author: '手绘君',
  time: '2026.02'
})
</script>

<template>
  <h1>{{ title }}</h1>
  <p>作者:{{ info.author }} | 时间:{{ info.time }}</p>
</template>

<style scoped>
/* scoped样式只作用于当前组件,不会污染全局 */
h1 {
  color: #42b983; /* Vue绿~ */
}
</style>

💡 新手小技巧(避坑!)

  1. 🚨 ref在模板里不用.value,JS里必须加!
  2. 📌 reactive只能绑对象/数组,简单类型用ref(ref更通用~)
  3. <script setup> 里定义的变量/方法,模板里直接用,不用return
  4. 🛑 Vue3移除了Vue2的filter,用计算属性替代就好

📋 常用API速记(手绘小抄)

API用途示例
ref简单类型响应式const num = ref(0)
reactive复杂类型响应式const obj = reactive({a:1})
computed计算属性const double = computed(() => num.value*2)
watch监听数据变化watch(num, (newVal) => {})
onMounted组件挂载后执行onMounted(() => {})

🎯 总结

  1. Vue3 核心是 Composition API,用 <script setup> 写代码更简洁;
  2. 响应式分 ref(简单类型)和 reactive(复杂类型),记住 ref 要加.value;
  3. 相比 Vue2,Vue3 更轻、更快、更灵活,还完美适配TS,新手直接学Vue3就对了~

✏️ 持续更新ing,随手画的笔记,有错欢迎指出来~