三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

vue3 开发知识点

vue3 开发知识点

一、Vue 3 开发基石

1️⃣ 创建应用

import{createApp}from'vue'importAppfrom'./App.vue'createApp(App).mount('#app')

2️⃣ 单文件组件(SFC)

<template> <div>{ { count }}</div> </template> <script setup lang="ts"> import { ref } from 'vue' const count = ref(0) </script>

二、响应式 API(开发核心)

✅ ref(基本类型)

constcount=ref(0)count.value++

const { name } = toRefs(user)
Vue 会自动把 value 转成 reactive
模板中:

{ { count }}

✅ reactive(对象)

conststate=reactive({name:'Tom',age:18})Object.assign(state,{name:'Jerry',age:20})

ref = 通用、可替换、推荐​
reactive = 仅限复杂对象、不可整体替换
官方推荐
优先使用 ref,只有在明确需要时才用 reactive

✅ computed(派生状态)

constdouble=computed(()=>count.value*2)

✅ watch / watchEffect

watch(监听明确数据)

watch(count,(newVal,oldVal)=>{console.log(newVal)})

watchEffect(自动收集依赖)

watchEffect(()=>{console.log(count.value)})

三、组件通信(开发高频)

1️⃣ props / emit(父子)

父组件

<Child :title="title" @change="handleChange" />

子组件

defineProps<{title:string}>()constemit=defineEmits<{change:[value:string]}>()

2️⃣ provide / inject(跨层级)

祖先组件

provide('theme','dark')

后代组件

consttheme=inject('theme')

3️⃣ v-model(双向绑定)

<Child v-model="name" />
defineProps<{modelValue:string}>()constemit=defineEmits(['update:modelValue'])

ref 获取子组件实例

<Childref="childRef"/>
const childRef=ref<InstanceType<typeof Child
← 返回列表