Vue3-Composition-API-学习笔记
01.Setup函数的体验
App.vue
<template><div><h2>当前计数:{{ counter }}</h2><button @click="increment">+1</button><button @click="decrement">-1</button></div>
</template><script>import useCounter from './hooks/useCounter'export default {setup(){// const { counter,increment,decrement } = useCounter()// return { counter,increment,decrement } return {...useCounter()}}}
</script><style scoped></style>
useCounter.js
import { ref } from 'vue'
export default function useCounter(){const counter = ref(100)const increment = () => {counter.value++console.log(counter.value)}const decrement = () =>{counter.value--}return { counter,increment,decrement }
}
02.Setup定义数据
App.vue
<template><div><form action="">账号:<input type="text" v-model="account.username">密码:<input type="password" v-model="account.password"></form></div>
</template><script>import { reactive,ref } from 'vue';export default{setup(){// 定义相应式数据:reactiveconst info = ref({})console.log(info.value)// 1. reactive的应用场景// 1.1 条件1:reactive的应用场景// 1.2 条件2:多个数据之间是有关系/联系的(聚合的数据,组织在一起会有特定的数作用)const account = reactive({username:"coderwhy",password:"123456"})return {account}}}
</script><style scoped></style>
App1.vue
<template><div><h2>message:{{ message }}</h2><button @click="changeMessage">修改message</button><hr><h2>账号:{{ account.username }}</h2><h2>密码:{{ account.password }}</h2><button @click="changeAccount">修改账号</button><hr><!-- 默认清空下在template中使用ref时,vue会自动进行千层解包(取出value) --><h2>当前计数:{{ counter }}</h2><button @click="increment">+1</button><hr><!-- 使用的时候 --><h2>当前计数:{{ info.counter }}</h2><!-- 修改的时候需要写.value --><button @click="info.counter.value++">+1</button></div>
</template><script>import { reactive,ref } from 'vue';export default {setup(){// 1.定义普通的数据// 缺点:数据不是响应式的let message = "Hello World"// 2.定义响应式数据// 2.1 reactive函数:定义复杂类型数据const account = reactive({username:"coderwhy",password:"123456"})function changeAccount(){account.username = "kobe"}function changeMessage() {message = "你好啊,李焕英"console.log(message)}// 2.2 counter定义响应式数据// ref函数:定义简单类型的数据const counter = ref(0)// const counter = reactive({// counter:0// })function increment(){counter.value++}// 3.ref是浅层解包const info = {counter}return {message,changeAccount,changeMessage,counter,account,increment,info}}}
</script><style scoped></style>
03.setup其他函数
App.vue
<template><div><h2>App</h2><ShowInfo @change_name="change_name" :reinfo="reinfo" @change_rename="change_rename" :info="info"></ShowInfo></div>
</template><script>import { reactive,readonly } from 'vue';import ShowInfo from './ShowInfo.vue';export default {components:{ShowInfo},setup(){const info = reactive({name:'kebo',age:18,sex:'男'})const reinfo = readonly(info)function change_name(eve){info.name = eve}function change_rename(reeve){info.name = reeve}return {info,change_name,reinfo,change_rename}},}
</script><style scoped></style>
ShowInfo.vue
<template><div><h2>info: {{ info }}</h2><button @click="change_name">改变info.name</button><hr><h2>reinfo:{{ reinfo }}</h2><!-- <button @click="reinfo.name='hahaha'">修改reinfo.name</button> --><button @click="change_rename">修改reinfo.name</button></div>
</template><script>export default {props:{info:{type:Object,default:() => ({})},reinfo:{type:Object,default:() => ({})},},emits:['change_name','change_rename'],setup(props,context){function change_name(){context.emit("change_name",'why')}function change_rename(){context.emit("change_rename",'tom')}return {change_name,change_rename}},methods:{}}
</script><style scoped></style>
04.Setup中toRefs
App.vue
<template><div><div>info:{{ info.name }} -- {{ info.age }}</div><div>name:{{ name }}---age:{{ age }}</div><button @click="age++">age+1</button><hr><div>height:{{ height }}</div><button @click="height++">height++</button></div>
</template><script>import { reactive,toRefs,toRef } from "vue";export default {setup(){const info = reactive({name:'tom',age:18,height:188})// reactive被结构将会编程普通的数据,失去响应式const { name,age } = toRefs(info)const height = toRef(info,"height")return {info,name,age,height}}}
</script><style scoped></style>
05.Setup中computed
App.vue
<template><div><div>fullname:{{ fullname }}</div><button @click="setFullname">设置fullname</button><div>scoreLevel:{{ scoreLevel }}</div></div>
</template><script>import { ref,reactive,computed } from 'vue'export default {setup(){// 1.定义数据const names = reactive({firstName:"kobe",lastName:"bryant"})// const fullname = computed(()=>{// return names.firstName +" "+ names.lastName// })const fullname = computed({set:function(newValue){const tempNames = newValue.split(" ")names.firstName = tempNames[0]names.lastName = tempNames[1]},get:function(){return names.firstName + " " + names.lastName}})console.log(fullname)function setFullname(){fullname.value = "coder why"console.log(names)}// 2.定义scoreconst score = ref(89)const scoreLevel = computed(()=>{return score.value >= 60 ? "及格" : "不及格"})return {names,fullname,scoreLevel,setFullname}}}
</script><style scoped></style>
06.Setup中ref引入元素
App.vue
<template><div><!-- 1.获取元素 --><h2 ref="titleRef"> 我是标题 </h2><button ref="btnRef">按钮</button><ShowInfo ref="ShowInfoRef"></ShowInfo><button @click="getElements">获取元素</button></div>
</template><script>import { ref,onMounted } from 'vue'import ShowInfo from './ShowInfo.vue'export default {// mounted(){// console.log(this.$refs.title)// console.log(this.$refs.btn)// }components:{ShowInfo},setup(){const titleRef = ref()const btnRef = ref()const ShowInfoRef = ref()// mounted的生命周期函数onMounted(()=>{console.log(titleRef.value)console.log(btnRef.value)console.log(ShowInfoRef.value)ShowInfoRef.value.ShowInfoFoo()})function getElements(){console.log(titleRef.value)}return {titleRef,getElements,btnRef,ShowInfoRef}}}
</script><style scoped></style>
ShowInfo.vue
<template><div><div>ShowInfo</div></div>
</template><script>export default {// methods:{// function ShowInfoFoo(){// console.log("showInfo foo function")// }// },setup(){function ShowInfoFoo(){console.log("showInfo foo function")}return {ShowInfoFoo}}}
</script><style scoped></style>
07.Setup生命周期函数
App.vue
<template><div></div>
</template><script>import { onMounted } from 'vue'export default {// created(){// },// beforeMount(){// },// mounted(){// },// beforeUpdate(){// },// updated(){// }setup(){// 在执行setup函数的过程中,你需要注册别的生命周期函数onMounted(()=>{console.log("onmounted")})}}
</script><style scoped></style>
08.Setup-Provide-Inject
App.vue
<template><div><div>App:{{ name }} --</div><ShowInfo></ShowInfo></div>
</template><script>import ShowInfo from './ShowInfo.vue';import { provide,ref } from 'vue'export default {components:{ShowInfo},setup(){const name = ref("why")provide("name",name)provide("age",18)return {name,}}}
</script><style scoped></style>
ShowInfo.vue
<template><div><div>showInfo:{{ name }} -- {{ age }}</div><button @click="name = 'kobe'">app btn</button></div>
</template><script>import { inject } from 'vue';export default {setup() {const name = inject("name");const age = inject("age");return {name,age};},
}
</script><style scoped></style>
09.Setup-侦听数据变化
App.vue
<template><div><div>当前计数 {{ counter }}</div><button @click="counter++">+1</button><button @click="change_name">修改name</button></div>
</template><script>import { ref,watchEffect } from 'vue'export default {setup(){const counter = ref(0);const name = ref('why');// 1.watchEffect传入的函数默认会直接被执行// 2.在执行过程中,会自动的收集依赖(以来那些响应式的数据)const stopWatch = watchEffect(()=>{console.log("------",counter.value,name.value)// 判断counter.value > 10if(counter.value >= 10){stopWatch()}})function change_name(){name.value='kobi'}return {counter,change_name,name}}}
</script><style scoped></style>
App-watch.vue
<template><div><h2>message:{{ message }}</h2><button @click="change_message">修改message</button><button @click="change_info">修改info</button></div>
</template><script>// import { watch } from 'fs'
import { ref,watch,reactive } from 'vue'export default {setup(){const message = ref('hello');const info = reactive({name:'tom',age:18,friend:{name:"kobe"}})function change_message(){message.value = '你好!'}function change_info(){info.name = 'hhhhh'}// 2.侦听变化watch(message,(newValue,oldValue)=>{console.log(newValue,oldValue)})// watch(info,(newValue,oldValue)=>{// console.log(newValue,oldValue)// console.log(newValue == oldValue)// },{// immediate:true // 深度侦听// }) // 3.监听reactive数据变化后,获取普通对象watch(()=>({ ...info }),(newValue,oldValue)=>{console.log(newValue,oldValue)},{immediate:true,deep:true})return {change_message,message,info,change_info}}}
</script><style scoped></style>
10.Setup-Hooks练习
App.vue
<template><div><div>App:{{ counter }}</div><button @click="increment">+1</button><button @click="decrement">-1</button><button @click="index_tab('首页-热门')">首页-热门</button><button @click="index_tab('首页-流行')">首页-流行</button><button @click="index_tab('首页-歌单')">首页-歌单</button><hr><HomeCom></HomeCom><hr><AboutCom></AboutCom></div>
</template><script>
import HomeCom from './views/HomeCom.vue';
import AboutCom from './views/AboutCom.vue';
import useCounter from './hooks/useCounter';
import useTitle from './hooks/useTitle';
export default {components: {HomeCom,AboutCom},setup() {const title = useTitle("首页")function index_tab(eve){title.value = eve}return {index_tab,...useCounter()}}
}
</script><style scoped></style>
AboutCom.vue
<template><div><div>About:{{ counter }}</div><button @click="increment">+1</button><button @click="decrement">-1</button><button @click="change_title">修改title</button></div>
</template><script>import useCounter from '../hooks/useCounter';import useTitle from '../hooks/useTitle';export default {setup(){const title = useTitle("首页")// 监听事件点击function change_title(){title.value = '关于';}return {change_title,...useCounter()}}}
</script><style scoped></style>
HomeCom.vue
<template><div><div>Home:{{ counter }}</div><button @click="increment">+1</button><button @click="decrement">-1</button></div>
</template><script>import useCounter from '../hooks/useCounter';export default {setup(){return {...useCounter()}}}
</script><style scoped></style>
useCounter.js
import { ref,onMounted } from 'vue'export default function useCounter(){const counter = ref(0)function increment(){counter.value++}function decrement(){counter.value--}onMounted(()=>{setTimeout(()=>{counter.value = 989},1000)})return {counter,increment,decrement}
}
useTitle.js
import { watch,ref } from "vue"export default function useTitle(titleValue){// document.title = title// 定义ref的引入数据const title = ref(titleValue)// 监听title的改变watch(title,(newValue)=>{document.title = newValue},{immediate:true // 第一次不执行})// 返回ref值return title
}
11.script_setup语法
App.vue
<template><div><div>App</div><button @click="changeMessage">修改message</button><show-info ref="showInfoRef" @info-btn-click="infoBtnClick" name="why" :age="18"></show-info> <!-- <ShowInfo></ShowInfo><ShowInfo></ShowInfo><ShowInfo></ShowInfo> --></div>
</template><script setup>
// 1. 所以定义在顶层中的代码,都是默认暴露给template可以使用import { onMounted,ref } from 'vue';import ShowInfo from './ShowInfo.vue';// 2. 定义响应式数据const message = ref("hello world")console.log(message)// 3. 定义绑定的函数function changeMessage(){message.value = "你好,世界"}function infoBtnClick(eve){console.log("监听到infoBtnClick内部的info",eve)}// 4. 获取组件实例const showInfoRef = ref();onMounted(()=>{showInfoRef.value.foo()console.log("showInfoRef.value.message",showInfoRef.value.message)})
</script><style scoped></style>
ShowInfo.vue
<template><div>message:-- {{ name }} --- {{ age }}<button @click="showInfoBtnClick">showinfo</button></div>
</template><script setup>
import { defineProps,defineEmits,defineExpose } from 'vue';const message = "hello world"// console.log(message)// 定义props const props = defineProps({name:{type:String,default:"默认值"},age:{type:Number,default:0}}) // 绑定函数,并发出事件const emits = defineEmits(["infoBtnClick"])function showInfoBtnClick(){emits("infoBtnClick","showInfo内部发生了点击")}// 定义foo的函数function foo(){console.log("foo function")}defineExpose({foo,message})</script><style scoped></style>
感谢大家观看,我们下次见
相关文章:
Vue3-Composition-API-学习笔记
01.Setup函数的体验 App.vue <template><div><h2>当前计数:{{ counter }}</h2><button click"increment">1</button><button click"decrement">-1</button></div> </template>&…...

NSS [HUBUCTF 2022 新生赛]checkin
NSS [HUBUCTF 2022 新生赛]checkin 判断条件是if ($data_unserialize[username]$username&&$data_unserialize[password]$password),满足则给我们flag。正常思路来说,我们要使序列化传入的username和password等于代码中的两个同名变量࿰…...

免费小程序HTTPS证书
随着互联网的快速发展,小程序已经成为人们日常生活中不可或缺的一部分。然而,在小程序的开发和使用过程中,安全问题一直是开发者们关注的重点。其中,HTTPS 证书是保障小程序安全的重要工具之一。在这方面,免费的小程序…...

Linux arm64异常简介和系统调用过程
文章目录 一、异常简介1.1 Exception levels1.2 异常类型 二、系统调用简介2.1 SVC指令2.2 VBAR2.3 系统调用保存现场2.4 系统调用返回 三、Linux 内核分析参考资料 一、异常简介 在ARM64体系架构中,异常是处理器在执行指令时可能遇到的不寻常情况或事件。这些异常…...
我遇到的最蠢的bug,竟然是因为这个原因……
bug的背景 我是一个Python开发者,我最近在做一个数据分析的项目,需要用到pandas库,来处理和分析一些表格数据我的功能需求是,根据用户输入的一些条件,从一个大的数据表中筛选出符合条件的数据,并生成一个新…...

【Mysql】查询mysql的版本
目录 cmd命令查询 mysql -- help(命令) mysql -u root -p(命令) 数据库管理工具查询 select version(); cmd命令查询 mysql -- help(命令) mysql -u root -p(命令) 执行该命令并且输入数据库密码 数据库管理工具查询 selec…...

广州华锐互动:VR互动实训内容编辑器助力教育创新升级
随着科技的飞速发展,教育领域也正在经历一场深刻的变革。其中,虚拟现实(VR)技术为教学活动提供了前所未有的便利和可能性。在诸多的VR应用中,VR互动实训内容编辑器无疑是最具潜力和创新性的一种。广州华锐互动开发的这款编辑器以其独特的功能…...

2023最新版本 从零基础入门C++与QT(学习笔记) -1- C++输入与输出
🎏说在前面 🎈我预计是使用两个月的时间玩转C与QT 🎈所以这是一篇学习笔记 🎈根据学习的效率可能提前完成学习,加油!!! 输入(代码如下方代码块) 🎄分析一下构成 🎈…...

Linux:权限篇 (彻底理清权限逻辑!)
shell命令以及运行原理: Linux严格意义上说的是一个操作系统,我们称之为“核心(kernel)“ ,但我们一般用户,不能直接使用kernel。而是通过kernel的“外壳”程序,也就是所谓的shell,来…...

classification_report分类报告的含义
classification_report分类报告 基础知识混淆矩阵(Confusion Matrix)TP、TN、FP、FN精度(Precision)准确率(Accuracy)召回率(Recall)F1分数(F1-score) classi…...
mysql with 的用法 (含 with recursive)
mysql with 的用法 (含 with recursive) 相关基础 AS 用法 as 在 mysql 中用来给列/表起别名 如: -- 给列起别名, 把列为name的别名命名为student_name select name as student_name from student; -- 给表起别名, 把表student的别名命名为data_list select * from student…...

YOLOv8模型ONNX格式INT8量化轻松搞定
ONNX格式模型量化 深度学习模型量化支持深度学习模型部署框架支持的一种轻量化模型与加速模型推理的一种常用手段,ONNXRUNTIME支持模型的简化、量化等脚本操作,简单易学,非常实用。 ONNX 模型量化常见的量化方法有三种:动态量化…...

揭秘南卡开放式耳机创新黑科技,核心技术剑指用户痛点
随着科技的进步和人们娱乐方式的升级,大家对听音工具的选择,从传统的耳机到蓝牙耳机再到AirPods这样的真无线耳机,而今年,也有一种全新的耳机爆发式涌入人们之中,那就是开放式耳机。 开放式耳机的出现,满足…...

ChatRule:基于知识图推理的大语言模型逻辑规则挖掘11.10
ChatRule:基于知识图推理的大语言模型逻辑规则挖掘 摘要引言相关工作初始化和问题定义方法实验 摘要 逻辑规则对于揭示关系之间的逻辑联系至关重要,这可以提高推理性能并在知识图谱(KG)上提供可解释的结果。虽然已经有许多努力&a…...

6.4翻转二叉树(LC226—送分题,前序遍历)
算法: 第一想法是用昨天的层序遍历,把每一层level用切片反转。但是这样时间复杂度很高。 其实只要在遍历的过程中去翻转每一个节点的左右孩子就可以达到整体翻转的效果。 这道题目使用前序遍历和后序遍历都可以,唯独中序遍历不方便&#x…...

【斗罗二】霍雨浩拿下满分碾压戴华斌,动用家族力量,海神阁会议
Hello,小伙伴们,我是小郑继续为大家深度解析国漫资讯。 深度爆料《绝世唐门》第23话最新预告分析,魂兽升学考试中一场白虎魂师戴华斌与千年级别的风虎的决斗即将上演。风虎,作为虎类魂兽的王者,其强大的实力和独特的技能让这场战…...

通义千问, 文心一言, ChatGLM, GPT-4, Llama2, DevOps 能力评测
引言 “克隆 dev 环境到 test 环境,等所有服务运行正常之后,把访问地址告诉我”,“检查所有项目,告诉我有哪些服务不正常,给出异常原因和修复建议”,在过去的工程师生涯中,也曾幻想过能够通过这…...

一键创建PDF文档,高效管理您的文件资料
在繁忙的工作中,您是否曾为处理PDF文件而感到烦恼?现在,我们为您推荐一款全新的高效PDF文档管理工具——一键创建PDF文档,让您的工作效率瞬间提升! 首先,在首助编辑高手的主页面板块栏里,选择“…...
React在 JSX 中进行条件渲染和循环,并使用条件语句和数组的方法(如 map)来动态生成组件或元素
在 JSX 中进行条件渲染和循环,你可以使用条件语句(如 if-else)和数组的方法(如 map)来动态生成组件或元素。以下是一些示例来说明这些概念: 条件渲染: import React from react;const MyCompo…...
数据结构-二叉树的遍历及相关应用
1、定义二叉树结点结构 2、编写主程序 3、三种方法遍历二叉树,并实现求树的深度,叶子数,某一层的结点数 4、实现代码(带交互界面) #include<iostream> using namespace std; typedef struct BiTNode {char d…...

MPNet:旋转机械轻量化故障诊断模型详解python代码复现
目录 一、问题背景与挑战 二、MPNet核心架构 2.1 多分支特征融合模块(MBFM) 2.2 残差注意力金字塔模块(RAPM) 2.2.1 空间金字塔注意力(SPA) 2.2.2 金字塔残差块(PRBlock) 2.3 分类器设计 三、关键技术突破 3.1 多尺度特征融合 3.2 轻量化设计策略 3.3 抗噪声…...
Java 语言特性(面试系列2)
一、SQL 基础 1. 复杂查询 (1)连接查询(JOIN) 内连接(INNER JOIN):返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

【网络安全产品大调研系列】2. 体验漏洞扫描
前言 2023 年漏洞扫描服务市场规模预计为 3.06(十亿美元)。漏洞扫描服务市场行业预计将从 2024 年的 3.48(十亿美元)增长到 2032 年的 9.54(十亿美元)。预测期内漏洞扫描服务市场 CAGR(增长率&…...
土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等
🔍 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术,可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势,还能有效评价重大生态工程…...
Spring AI 入门:Java 开发者的生成式 AI 实践之路
一、Spring AI 简介 在人工智能技术快速迭代的今天,Spring AI 作为 Spring 生态系统的新生力量,正在成为 Java 开发者拥抱生成式 AI 的最佳选择。该框架通过模块化设计实现了与主流 AI 服务(如 OpenAI、Anthropic)的无缝对接&…...

k8s业务程序联调工具-KtConnect
概述 原理 工具作用是建立了一个从本地到集群的单向VPN,根据VPN原理,打通两个内网必然需要借助一个公共中继节点,ktconnect工具巧妙的利用k8s原生的portforward能力,简化了建立连接的过程,apiserver间接起到了中继节…...

初学 pytest 记录
安装 pip install pytest用例可以是函数也可以是类中的方法 def test_func():print()class TestAdd: # def __init__(self): 在 pytest 中不可以使用__init__方法 # self.cc 12345 pytest.mark.api def test_str(self):res add(1, 2)assert res 12def test_int(self):r…...

让回归模型不再被异常值“带跑偏“,MSE和Cauchy损失函数在噪声数据环境下的实战对比
在机器学习的回归分析中,损失函数的选择对模型性能具有决定性影响。均方误差(MSE)作为经典的损失函数,在处理干净数据时表现优异,但在面对包含异常值的噪声数据时,其对大误差的二次惩罚机制往往导致模型参数…...
虚拟电厂发展三大趋势:市场化、技术主导、车网互联
市场化:从政策驱动到多元盈利 政策全面赋能 2025年4月,国家发改委、能源局发布《关于加快推进虚拟电厂发展的指导意见》,首次明确虚拟电厂为“独立市场主体”,提出硬性目标:2027年全国调节能力≥2000万千瓦࿰…...

[论文阅读]TrustRAG: Enhancing Robustness and Trustworthiness in RAG
TrustRAG: Enhancing Robustness and Trustworthiness in RAG [2501.00879] TrustRAG: Enhancing Robustness and Trustworthiness in Retrieval-Augmented Generation 代码:HuichiZhou/TrustRAG: Code for "TrustRAG: Enhancing Robustness and Trustworthin…...