Vue3 组合式 API 实战

最近在详细学习vue3的知识点,通过小案例可以更融会贯通的理解,为了更好地理解 setup()ref()reactive()computed()watch() 等核心概念,我决定动手实现一个「任务清单 TodoList」。 这篇文章将记录我学习到的知识点

核心知识点:

(1)ref 与 reactive:

ref:基本数据类型,reactive:数组,对象

(2)computed实现任务筛选:

js 复制代码
const filteredTodos = computed(() => {
  if (filter.value === 'active') return todos.filter(t => !t.done)
  if (filter.value === 'completed') return todos.filter(t => t.done)
  return todos
})

组件通信:

  1. 父组件到子组件的通信(props)
    父组件通过props将数据传递给子组件,子组件接受的props是只读的
xml 复制代码
<!-- Parent.vue -->
<template>
<Child :message="parentMessage" />
</template>

<!-- Child.vue -->
<template>
<p>{{ message }}</p>
</template>
<script>
const props =defineProps({
message : String})
</script

2.props的写法

(1)基本对象类型声明:

js 复制代码
<script>
 const props = defineProps({
     message:{
       type:String,
       default: 0,
       required: true
     }
     
 })
</script>

(2)ts格式

ts 复制代码
<script setup lang="ts">
interface Props {
  title: string
  count?: number
}

const props = defineProps<Props>()
</script>

(3)数组形式

xml 复制代码
<script setup>
const props = defineProps(['title', 'count'])
</script>

3.子组件到父组件通信(emit):

子组件通过$emit向父组件发送事件,父组件监听并获取带过来的参数

xml 复制代码
<!-- Parent.vue -->
<template>
  <Child @update="handleUpdate" />
</template>

<!-- child.vue -->
<button @click="sendUpdate">Send to Parent</button>
<script>
const emit = defineEmits(['update'])
function sendUpdate() {
  emit('update', 'Hello Parent')
}
<script>

v-model的自定义事件

  1. 在v-model中通过prop和emit进行数据的双向绑定,在此中了解明白其双向数据流动的解基本原理
  • prop:value -> modelValue
  • 事件:input -> update:modelValue
  • 新增 支持多个v-model
  • 新增 支持自定义 修饰符 Modifiers
  1. 在这里先只了解学习基本用法
xml 复制代码
 <div>
  我是父组件:<input type="text" v-model="isfu">
 </div>
 <v-model v-model="isfu"></v-model>

</template>
<script setup lang='ts'>
import { ref } from 'vue';
import vModel from './components/v-model.vue';
const isfu =ref('')

 <div>
  我是子组件:
  <input type="text" :value="modelValue" @input="sent">
 </div>

</template>
<script setup lang='ts'>
const prop =defineProps({
  modelValue:{
    type:String
  }
})
const emit =defineEmits(['update:modelValue'])
const sent =(e:Event)=>{
  emit('update:modelValue',(e.target as HTMLInputElement ).value)
  
}
</script>

子组件通过prop接收,emit再将数据发送给父组件

相关推荐
秋田君4 小时前
3D热力图封装组件:Vue + Three.js 实现3D图表详解
javascript·vue.js·3d·three.js·热力图
一枚前端小能手4 小时前
🔄 重学Vue之生命周期 - 从源码层面解析到实战应用的完整指南
前端·javascript·vue.js
晓得迷路了5 小时前
栗子前端技术周刊第 103 期 - Vitest 4.0、Next.js 16、Vue Router 4.6...
前端·javascript·vue.js
咖啡の猫7 小时前
Vue混入
前端·javascript·vue.js
两个西柚呀11 小时前
未在props中声明的属性
前端·javascript·vue.js
一个处女座的程序猿O(∩_∩)O15 小时前
Vue-Loader 深度解析:原理、使用与最佳实践
前端·javascript·vue.js
麦麦大数据17 小时前
F034 vue+neo4j 体育知识图谱系统|体育文献知识图谱vue+flask知识图谱管理+d3.js可视化
javascript·vue.js·知识图谱·neo4j·文献·体育·知识图谱管理
fhsWar19 小时前
Vue3 props: `required: true` 与 vant 的`makeRequiredProp`
前端·javascript·vue.js
阿珊和她的猫1 天前
深入剖析 Vue Router History 路由刷新页面 404 问题:原因与解决之道
前端·javascript·vue.js