第Ⅷ章-Ⅱ 组合式API使用
第Ⅷ章-Ⅱ 组合式API使用
- provide与inject的使用
- vue 生命周期的用法
- 编程式路由的使用
- vuex的使用
- 获取DOM的使用
- setup语法糖
- setup语法糖的基本结构
- 响应数据的使用
- 其它语法的使用
- 引入组件的使用
- 父组件传值的使用
- defineProps 父传子
- defineEmits 子传父
provide与inject的使用
provide 与 inject 是 Vue 3 中用于跨组件树传递数据的 API,适合解决深层嵌套组件的通信问题。
- provide:父组件提供数据。
- inject:子组件接收数据。
<!-- src/App.vue -->
<template><div><ProviderComponent /></div>
</template><script setup>
import ProviderComponent from './components/ProviderComponent.vue';
</script>
<!-- src/components/ProviderComponent.vue -->
<template><div><h1>Provider Component</h1><ChildComponent /></div>
</template><script setup>
import { provide } from 'vue';
import ChildComponent from './ChildComponent.vue';const providedData = 'Hello from Provider!';
provide('message', providedData);
</script>
<!-- src/components/ChildComponent.vue -->
<template><div><h2>Child Component</h2><p>{{ message }}</p></div>
</template><script setup>
import { inject } from 'vue';const message = inject<string>('message', 'Default Message');
</script>
vue 生命周期的用法
Vue 3 引入了组合式 API,使得生命周期钩子以函数形式使用,增加了灵活性。
<template><div>{{ message }}</div>
</template><script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';const message = ref('Hello, Vue 3!');onMounted(() => {console.log('Component is mounted');message.value = 'Component Mounted';
});onBeforeUnmount(() => {console.log('Component is about to unmount');
});
</script>
编程式路由的使用
Vue Router 支持编程式路由跳转,可以使用 router.push 和 router.replace。
<!-- src/components/NavigationComponent.vue -->
<template><div><button @click="goToHome">Go to Home</button><button @click="replaceWithAbout">Replace with About</button><button @click="goBack">Go Back</button></div>
</template><script setup>
import { useRouter } from 'vue-router';const router = useRouter();const goToHome = () => {router.push('/home');
};const replaceWithAbout = () => {router.replace('/about');
};const goBack = () => {router.go(-1);
};
</script>
vuex的使用
Vuex 是 Vue 官方的状态管理库,通常使用 createStore 创建全局 store。
// src/store/index.ts
import { createStore } from 'vuex';interface State {count: number;
}const store = createStore<State>({state: {count: 0},mutations: {increment(state) {state.count += 1;},decrement(state) {state.count -= 1;}},actions: {incrementAsync({ commit }) {setTimeout(() => {commit('increment');}, 1000);}},getters: {doubleCount(state) {return state.count * 2;}}
});export default store;
在组件中使用 Vuex 状态和方法
<!-- src/components/CounterComponent.vue -->
<template><div><h2>Counter Example</h2><p>Count: {{ count }}</p><p>Double Count (getter): {{ doubleCount }}</p><button @click="increment">Increment</button><button @click="decrement">Decrement</button><button @click="incrementAsync">Increment Async</button></div>
</template><script setup lang="ts">
import { computed } from 'vue';
import { useStore } from 'vuex';const store = useStore();const count = computed(() => store.state.count);
const doubleCount = computed(() => store.getters.doubleCount);
const increment = () => store.commit('increment');
const decrement = () => store.commit('decrement');
const incrementAsync = () => store.dispatch('incrementAsync');
</script>
获取DOM的使用
在组合式 API 中可以使用 ref 和 onMounted 钩子来访问 DOM 元素。
<template><div><input type="text" ref="inputElement" placeholder="Type something..." /><button @click="focusInput">Focus Input</button></div>
</template><script setup lang="ts">
import { ref, onMounted } from 'vue';const inputElement = ref<HTMLInputElement | null>(null);const focusInput = () => {inputElement.value?.focus();
};onMounted(() => {console.log('Component Mounted and DOM is ready');
});
</script>
setup语法糖
setup 语法糖 在 Vue 3.3 中引入,它简化了 setup 函数的使用,使得代码更加简洁易读。
setup语法糖的基本结构
<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>
响应数据的使用
- ref:创建单一响应式值。
- reactive:创建响应式对象。
- toRefs:将 reactive 对象转换为 ref 对象。
<template><div><p>{{ message }}</p><p>Counter: {{ count }}</p></div>
</template><script setup>
import { ref, reactive, toRefs } from 'vue';const message = ref('Hello, Vue 3!');
const state = reactive({ count: 0 });const { count } = toRefs(state);
</script>
其它语法的使用
- computed:创建计算属性。
- watch:观察响应式数据的变化并执行副作用。
<template><div><p>Double Count: {{ doubleCount }}</p><input v-model="name" placeholder="Name" /><p>{{ name }}</p></div>
</template><script setup>
import { ref, computed, watch } from 'vue';const count = ref(2);
const doubleCount = computed(() => count.value * 2);const name = ref('Alice');
watch(name, (newValue, oldValue) => {console.log(`Name changed from ${oldValue} to ${newValue}`);
});
</script>
引入组件的使用
<!-- src/App.vue -->
<template><CounterComponent />
</template><script setup>
import CounterComponent from './components/CounterComponent.vue';
</script>
父组件传值的使用
defineProps 父传子
<!-- src/components/ChildComponent.vue -->
<template><p>{{ message }}</p>
</template><script setup>
import { defineProps } from 'vue';const props = defineProps({message: String
});
</script>
<!-- src/App.vue -->
<template><ChildComponent message="Hello, Child!" />
</template><script setup>
import ChildComponent from './components/ChildComponent.vue';
</script>
defineEmits 子传父
<!-- src/components/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>
<!-- src/App.vue -->
<template><ChildComponent @message="handleMessage" /><p>{{ parentMessage }}</p>
</template><script setup>
import { ref } from 'vue';
import ChildComponent from './components/ChildComponent.vue';const parentMessage = ref('');const handleMessage = (msg: string) => {parentMessage.value = msg;
};
</script>
相关文章:
第Ⅷ章-Ⅱ 组合式API使用
第Ⅷ章-Ⅱ 组合式API使用 provide与inject的使用vue 生命周期的用法编程式路由的使用vuex的使用获取DOM的使用setup语法糖setup语法糖的基本结构响应数据的使用其它语法的使用引入组件的使用 父组件传值的使用defineProps 父传子defineEmits 子传父 provide与inject的使用 pro…...

stable-diffusion-webui配置
源码地址 https://github.com/AUTOMATIC1111/stable-diffusion-webui.git报错Fresh install fail to load AttributeError: NoneType object has no attribute _id pydantic降级 pip uninstall pydantic pip install pydantic1.10.11记得要把clip-vit-large-patch14放在opena…...

1+X电子商务数据采集渠道及工具选择(二)||电商数据采集API接口
电商数据采集API 接口 ◆适用范围 淘宝:可以采集到所属淘宝、天猫店铺的流量、销售、产品、运营相关数据;需要采集行业市场数据,则需要选择市场行情版。 京东:采集京东等其他平台店铺数据 jd.item_get 公共参数 名称类型必须描述keyString是调用key&…...

apinto OpenAPI
OpenApi 上游 查询列表 查询详情 新增 { "name": "jg_upstream", "driver": "http", "description": "通过postman添加上游", "scheme": "HTTPS", "retry":"1", "…...

XYCTF - web
目录 warm up ezMake ezhttp ezmd5 牢牢记住,逝者为大 ezPOP 我是一个复读机 ezSerialize 第一关 第二关 第三关 第一种方法: 第二种方法: ez?Make 方法一:利用反弹shell 方法二:通过进制编码绕过 ε…...

学习方法的重要性
原贴:https://www.cnblogs.com/feily/p/13999204.html 原贴:https://36kr.com/p/1236733055209095 1、 “一万小时定律”的正确和误区 正确: 天才和大师的非凡,不是真的天资超人一等,而是付出了持续不断的努力&…...
把现有的 Jenkins 容器推送到一个新的镜像标签,并且重新启动新的容器
要把现有的 Jenkins 容器推送到一个新的镜像标签,并且重新启动新的容器,你可以按照以下步骤操作: 停止当前正在运行的 Jenkins 容器(如果你不想在操作时中断服务,可以跳过此步骤,直接进行下一步)…...

难以重现的 Bug如何处理
对很多测试人员(尤其是对新手来说)在工作过程中最不愿遇到的一件事情就是:在测试过 程中发现了一个问题,觉得是 bug,再试的时候又正常了。 碰到这样的事情,职业素养和测试人员长期养成的死磕的习性会让她…...

我与足球的故事 | 10年的热爱 | 伤病 | 悔恨 | 放弃 or 继续 | 小学生的碎碎念罢了
今天不分享技术博客,今天不知道为什么就是想写我和足球的故事(手术完两个礼拜,手还是很疼那个,就连打字都费劲),上面两张图是我最喜欢的两个球星,当然因为之前特别喜欢巴萨,也特别喜…...

js图片回显的方法
直接上代码: <!DOCTYPE html> <html><head><meta charset"utf-8"><title></title></head><body>// HTML部分<input type"file" id"fileInput"><button onclick"show…...

Java中的maven的安装和配置
maven的作用 依赖管理 方便快捷的管理项目依赖的资源,避免版本冲突问题 统一项目管理 提供标准,统一的项目结构 项目构建 标准跨平台(Linux、windows、MacOS)的自动化项目构建方式 maven的安装和配置 在maven官网下载maven Ma…...

轴承制造企业“数智化”突破口
轴承是当代机械设备中一种重要零部件。它的主要功能是支撑机械旋转体,降低其运动过程中的摩擦系数,并保证其回转精度。轴承是工业核心基础零部件,对国民经济发展和国防建设起着重要的支撑作用。 轴承企业普遍采用以销定产的经营模式…...
UIButton案例之添加动画
需求 基于上一节代码进行精简,降低了冗余性。添加动画,使得坐标变化自然,同时使用了bounds属性和center属性,使得UIView变化以中心点为基准。 此外,使用两种方式添加动画:1.原始方式。 2.block方式。 代码…...
C#链接数据库、操作sql、选择串口
// 公共增删方法 using MySql.Data.MySqlClient; using System.Data; namespace ****** {public class MySQLHelper{private MySqlConnection conn null;private MySqlCommand comm null;private MySqlDataReader reader null;/// <summary>/// 构造方法里建议连…...

本地搭建各大直播平台录屏服务结合内网穿透工具实现远程管理录屏任务
文章目录 1. Bililive-go与套件下载1.1 获取ffmpeg1.2 获取Bililive-go1.3 配置套件 2. 本地运行测试3. 录屏设置演示4. 内网穿透工具下载安装5. 配置Bililive-go公网地址6. 配置固定公网地址 本文主要介绍如何在Windows系统电脑本地部署直播录屏利器Bililive-go,并…...

macos使用yarn创建vite时出现Usage Error: The nearest package directory问题
步骤是macos上使用了yarn create vite在window上是直接可以使用了yarn但是在macos上就出现报错 我们仔细看,它说的If /Users/chentianyu isnt intended to be a project, remove any yarn.lock and/or package.json file there.说是要我们清除yarn.lock和package.js…...

【JAVA入门】Day04 - 方法
【JAVA入门】Day04 - 方法 文章目录 【JAVA入门】Day04 - 方法一、方法的格式1.1 无参无返回值的方法定义和调用1.2 带参数的方法定义和调用1.3 形参和实参1.4 带返回值的方法定义和调用1.5 方法的注意事项 二、方法的重载三、方法的使用四、方法的内存原理4.1 方法调用的基本内…...

前端报错 SyntaxError: Unexpected number in JSON at position xxxx at JSON.parse
问题描述 控制台提示 SyntaxError: Unexpected number in JSON at position xxxx at JSON.parse 问题原因 原因:JSON 数据格式错误,是否符合 JSON 格式。 解决方法 应为json格式数据 什么是json格式数据 JSON(JavaScript Object …...

Mybatis进阶详细用法
目录 条件构造器 案例 自定义SQL 案例 Service接口 案例 综合案例 条件构造器 案例 Testvoid testQueryMapper() {// 创建 QueryWrapper 实例QueryWrapper<User> queryWrapper new QueryWrapper<>();queryWrapper.select("id," "username,&…...

Android 系统省电软件分析
1、硬件耗电 主要有: 1、屏幕 2、CPU 3、WLAN 4、感应器 5、GPS(目前我们没有) 电量其实是目前手持设备最宝贵的资源之一,大多数设备都需要不断的充电来维持继续使用。不幸的是,对于开发者来说,电量优化是他们最后才会考虑的的事情…...

2025年能源电力系统与流体力学国际会议 (EPSFD 2025)
2025年能源电力系统与流体力学国际会议(EPSFD 2025)将于本年度在美丽的杭州盛大召开。作为全球能源、电力系统以及流体力学领域的顶级盛会,EPSFD 2025旨在为来自世界各地的科学家、工程师和研究人员提供一个展示最新研究成果、分享实践经验及…...
vue3 字体颜色设置的多种方式
在Vue 3中设置字体颜色可以通过多种方式实现,这取决于你是想在组件内部直接设置,还是在CSS/SCSS/LESS等样式文件中定义。以下是几种常见的方法: 1. 内联样式 你可以直接在模板中使用style绑定来设置字体颜色。 <template><div :s…...
【git】把本地更改提交远程新分支feature_g
创建并切换新分支 git checkout -b feature_g 添加并提交更改 git add . git commit -m “实现图片上传功能” 推送到远程 git push -u origin feature_g...

Linux 中如何提取压缩文件 ?
Linux 是一种流行的开源操作系统,它提供了许多工具来管理、压缩和解压缩文件。压缩文件有助于节省存储空间,使数据传输更快。本指南将向您展示如何在 Linux 中提取不同类型的压缩文件。 1. Unpacking ZIP Files ZIP 文件是非常常见的,要在 …...

LLMs 系列实操科普(1)
写在前面: 本期内容我们继续 Andrej Karpathy 的《How I use LLMs》讲座内容,原视频时长 ~130 分钟,以实操演示主流的一些 LLMs 的使用,由于涉及到实操,实际上并不适合以文字整理,但还是决定尽量整理一份笔…...

Golang——6、指针和结构体
指针和结构体 1、指针1.1、指针地址和指针类型1.2、指针取值1.3、new和make 2、结构体2.1、type关键字的使用2.2、结构体的定义和初始化2.3、结构体方法和接收者2.4、给任意类型添加方法2.5、结构体的匿名字段2.6、嵌套结构体2.7、嵌套匿名结构体2.8、结构体的继承 3、结构体与…...
微服务通信安全:深入解析mTLS的原理与实践
🔥「炎码工坊」技术弹药已装填! 点击关注 → 解锁工业级干货【工具实测|项目避坑|源码燃烧指南】 一、引言:微服务时代的通信安全挑战 随着云原生和微服务架构的普及,服务间的通信安全成为系统设计的核心议题。传统的单体架构中&…...

macOS 终端智能代理检测
🧠 终端智能代理检测:自动判断是否需要设置代理访问 GitHub 在开发中,使用 GitHub 是非常常见的需求。但有时候我们会发现某些命令失败、插件无法更新,例如: fatal: unable to access https://github.com/ohmyzsh/oh…...

【51单片机】4. 模块化编程与LCD1602Debug
1. 什么是模块化编程 传统编程会将所有函数放在main.c中,如果使用的模块多,一个文件内会有很多代码,不利于组织和管理 模块化编程则是将各个模块的代码放在不同的.c文件里,在.h文件里提供外部可调用函数声明,其他.c文…...
SQL进阶之旅 Day 22:批处理与游标优化
【SQL进阶之旅 Day 22】批处理与游标优化 文章简述(300字左右) 在数据库开发中,面对大量数据的处理任务时,单条SQL语句往往无法满足性能需求。本篇文章聚焦“批处理与游标优化”,深入探讨如何通过批量操作和游标技术提…...