第Ⅷ章-Ⅰ 组合式API初识

server/2024/9/23 2:40:40/

第Ⅷ章-Ⅰ 组合式API初识

  • 简介
    • setup 函数
  • 为什么要使用Composition API
    • 逻辑复用和组织
    • 更灵活的逻辑组合
    • 适应未来的 Vue 生态系统
  • options API存在的问题
    • 代码重复:
    • 逻辑分散
    • 缺乏复用性
  • Composition API 中的 setup()入口
    • props 参数
    • context 参数
  • ref 响应式监听
  • reactive与toRefs
    • reactive
    • toRefs
  • computed的用法
  • watch的用法
  • setup()参数 props参数
  • context参数
    • emit
    • attrs
    • slots

简介

Composition API 是 Vue 3 引入的一种新的编写组件逻辑的方式。它通过将组件的逻辑按功能性分组,而不是按生命周期分组,从而提供更灵活的组件逻辑组合方式。Composition API 的核心是 setup 函数,组件内的逻辑通常在 setup 中定义。以下是它的基本概念:

setup 函数

  • 是组件逻辑的入口点,在组件实例创建时被调用。
  • 接收两个参数 props 和 context。
  • 返回的对象属性可以被模板中直接访问。
<!-- 使用 Composition API 的基本示例 -->
<template><div>{{ message }}</div><button @click="increment">Increment: {{ count }}</button>
</template><script setup>
import { ref } from 'vue';const message = ref('Hello, Vue 3!');
const count = ref(0);const increment = () => {count.value++;
};
</script>

为什么要使用Composition API

逻辑复用和组织

  • 问题:在选项式 API 中,组件的逻辑通常分散在 data、methods、computed 等属性中,很难复用和维护。
  • 解决方案:Composition API 可以将相关的逻辑组合在一起,并可以通过自定义组合函数轻松复用逻辑。

更灵活的逻辑组合

  • Composition API 提供了组合逻辑的自由度,可以更清晰地组织组件的功能。

适应未来的 Vue 生态系统

  • Vue 3 和未来的 Vue 工具链都将大量使用 Composition API,因此尽早熟悉它会有助于适应未来的 Vue 生态系统。

options API存在的问题

代码重复:

逻辑相似的功能会在不同的组件中重复出现。

逻辑分散

同一功能的逻辑会分散在 data、methods、computed 和 watch 中,不易追踪。

缺乏复用性

尽管 mixins 可以复用一些逻辑,但存在命名冲突和可读性问题。

Composition API 中的 setup()入口

setup() 函数是 Composition API 的入口点,所有的组件逻辑都可以在这里定义。它接收两个参数 props 和 context。

props 参数

组件接收的属性,具有响应性。

context 参数

包含 attrs、slots 和 emit 属性
attrs:包含没有被显式声明的 props。
slots:传入的插槽内容。
emit:用于触发事件。

ref 响应式监听

ref 函数用于创建单一响应式值,它将一个普通数据类型或对象包装成响应式的引用,并且返回一个包含 .value 属性的对象。

<template><div>Count: {{ count }}</div><button @click="increment">Increment</button>
</template><script setup>
import { ref } from 'vue';const count = ref(0);const increment = () => {count.value++;
};
</script>

reactive与toRefs

reactive

将一个对象变为响应式对象。

<template><div><p>Name: {{ user.name }}</p><p>Age: {{ user.age }}</p></div>
</template><script setup>
import { reactive } from 'vue';const user = reactive({name: 'Alice',age: 30
});
</script>

toRefs

将 reactive 对象中的属性转换为 ref,以便可以解构和保持响应性。

<template><div><p>Name: {{ name }}</p><p>Age: {{ age }}</p></div>
</template><script setup>
import { reactive, toRefs } from 'vue';const user = reactive({name: 'Alice',age: 30
});const { name, age } = toRefs(user);
</script>

computed的用法

computed 用于定义基于其他响应式属性的计算属性,类似于选项式 API 中的 computed 属性。

<template><p>Double Count: {{ doubleCount }}</p>
</template><script setup>
import { ref, computed } from 'vue';const count = ref(2);
const doubleCount = computed(() => count.value * 2);
</script>

watch的用法

watch 用于观察响应式属性的变化并执行副作用操作。

<template><div><input v-model="name" placeholder="Name" /><p>{{ name }}</p></div>
</template><script setup>
import { ref, watch } from 'vue';const name = ref('Alice');watch(name, (newValue, oldValue) => {console.log(`Name changed from ${oldValue} to ${newValue}`);
});
</script>

setup()参数 props参数

props 是 setup 函数的第一个参数,包含父组件传递的属性。它是响应式的,但是不能解构,否则会失去响应性。

<!-- ParentComponent.vue -->
<template><ChildComponent message="Hello, Child!" />
</template><script setup>
import ChildComponent from './ChildComponent.vue';
</script>
<!-- ChildComponent.vue -->
<template><div>{{ message }}</div>
</template><script setup>
import { defineProps } from 'vue';// 使用 defineProps
const props = defineProps({message: String
});
</script>

context参数

context 是 setup 函数的第二个参数,包含 attrs、slots 和 emit 属性。

emit

用于触发事件,类似于选项式 API 中的 $emit。

<!-- ParentComponent.vue -->
<template><ChildComponent @message="handleMessage" /><p>{{ parentMessage }}</p>
</template><script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';const parentMessage = ref('');const handleMessage = (msg: string) => {parentMessage.value = msg;
};
</script>
<!-- ChildComponent.vue -->
<template><button @click="sendMessage">Send Message to Parent</button>
</template><script setup>
import { defineEmits } from 'vue';const emit = defineEmits(['message']);const sendMessage = () => {emit('message', 'Hello from Child Component!');
};
</script>

attrs

包含没有显式声明的属性和事件。

<template><input v-bind="attrs" />
</template><script setup>
import { useAttrs } from 'vue';const attrs = useAttrs();
</script>

slots

包含传递的插槽内容。

<!-- ParentComponent.vue -->
<template><ChildComponent><template #header><h1>Custom Header</h1></template></ChildComponent>
</template><script setup>
import ChildComponent from './ChildComponent.vue';
</script>
<!-- ChildComponent.vue -->
<template><slot name="header"></slot><p>Default Content</p>
</template><script setup>
import { useSlots } from 'vue';const slots = useSlots();
</script>

http://www.ppmy.cn/server/39525.html

相关文章

Elastic Stack--04-1--Kibana查数

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 Kibana查数1.查询所有记录2.匹配id字段matchterm 3.bool[复合查询]4.业务查询 Kibana查数 在ElasticSearch中支持两种检索方式 通过使用REST request URL 发送检索…

神经网络与空间变换关系

神经网络的隐藏层实际上就是在进行一次空间变换&#xff0c;隐藏层中神经元的个数就是变换后空间的维度&#xff0c;代表可以升维也可以降维。 不同是 神经网络的一层运算不只有矩阵乘法&#xff0c;还会有一个加法。以及 进行完线性计算后&#xff0c;还要经过非线性的激活函…

sdut java lab7.2

7-2 sdut-JAVA-Words Containing AB 分数 9 全屏浏览 切换布局 作者 马新娟 单位 山东理工大学 Write a program that requests a word as input containing the two letters a and b (in this order). Examples of valid words would include, abacus, cab, and anybody, …

【MySQL基本查询(下)】

文章目录 一、update案例 二、Delete案例注意&#xff1a;delete 全表数据的行为慎用&#xff01;truncate 三、插入查询结果案例 四、了解一些函数1.count函数2.sum函数3. avg函数4.max函数5. min函数 五、group by子句的使用案例having和where 一、update 该关键字的功能就是…

ExcelVBA取序号与合计之间的数据

今天有人提出这样一个问题&#xff0c; ExcelVBA取序号与合计之间的数据 数据如下: 分析一下&#xff0c;问题关键&#xff1a; 问题&#xff1a;1.我要在“序号”两字后面开始取数&#xff0c;因为序号是合并的&#xff0c;所以。。。2.我要取合计前面的数据&#xff0c;所以要…

SpringCloud生态体系介绍

Spring Cloud是一系列框架的有序集合。它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发&#xff0c;如服务发现注册、配置中心、智能路由、消息总线、负载均衡、断路器、数据监控等&#xff0c;都可以用Spring Boot的开发风格做到一键启动和部署。 SpringC…

鸿蒙——即将是国内全部物联网的搭载系统

国内物联网时代 中国国内物联网时代是指在中国国内&#xff0c;物联网&#xff08;Internet of Things&#xff0c;简称IoT&#xff09;技术得到广泛应用和发展的时代。在这个时代&#xff0c;各种设备和物品都可以通过互联网进行连接和交互&#xff0c;实现信息的采集、传输和…

Go语言流程控制(二)

switch语句 Go 语言中的 switch 语句是一种选择结构&#xff0c;用于基于不同条件执行不同的代码块。Go 的 switch 相较于其他语言的 switch 有一些独特的特点&#xff0c;使其更为灵活和强大。下面是Go语言中 switch 语句的详细介绍&#xff1a; 基本语法 switch expressio…