这段代码的意思是:对itemList数组进行遍历,把每一项的age属性累加起来,最终得到所有age的总和。
代码拆解
itemList.reduce((pre, cur) => { return pre += cur.age }, 0)-
reduce方法:遍历数组,把每次计算的结果累积起来。 -
pre(累加器):上一次回调返回的结果,初始值是后面的0。 -
cur(当前项):当前遍历到的数组元素,在这里是itemList里的每个对象。 -
cur.age:取当前对象的age属性值。 -
return pre += cur.age:把当前项的年龄加到累加器上,并返回给下一次循环。
最终结果就是itemList里所有对象age属性的总和。
举个实际例子
const itemList = [ { name: '张三', age: 18 }, { name: '李四', age: 22 }, { name: '王五', age: 25 } ] const totalAge = itemList.reduce((pre, cur) => { return pre += cur.age }, 0) console.log(totalAge) // 输出 65几个容易踩的坑
- 必须传初始值
0:如果数组为空,不传初始值会直接报错;传了0则安全返回0。 -
pre += cur.age和pre + cur.age效果一样:+=会赋值,+只计算不赋值,但因为return都会返回结果,所以写法上等价。 - 回调里必须
return:如果忘了写return,累加器会变成undefined,结果就不对了。
在 Vue3 里的实际用法
通常在computed计算属性里配合使用,实现响应式求和:
import { ref, computed } from 'vue' const itemList = ref([ { name: '篮球', age: 2 }, { name: '足球', age: 5 }, { name: '羽毛球', age: 4 } ]) const totalAge = computed(() => { return itemList.value.reduce((pre, cur) => pre + cur.age, 0) })这样itemList里的数据变化时,totalAge会自动更新。
localStorage 本地存储
// localStorage 本地存储 // const localStorageToken = localStorage.getItem("token") // console.log("localStorageToken",localStorageToken) // // 本地存储 写入 // localStorage.setItem("token","123456") // // 本地存储 读取 // const token = localStorage.getItem("token") // console.log("token",token) // // 本地存储 删除 // localStorage.removeItem("token") // // 本地存储 清空 // localStorage.clear() // ***************************************************** 关键注意点 只能存字符串:localStorage 只能存字符串,存对象或数组必须先 JSON.stringify,取出来再 JSON.parse。 javascript // 存对象 const userInfo = { id: 1, name: '张三' } localStorage.setItem('userInfo', JSON.stringify(userInfo)) // 取对象 const stored = JSON.parse(localStorage.getItem('userInfo') || '{}') console.log(stored.name) // 张三 存储容量有限:一般限制在 5MB 左右,数据量太大会报错,别往里塞大文件或大量缓存数据。 删除:localStorage.removeItem('key') 删单个, 清空全部 :localStorage.clear() 进阶方案 1 :先安装:npm i @vueuse/core 2 :加载:import { useStorage } from '@vueuse/core'; 3 :删除 localstoreage 值: <button @click="clear">删除</button> # 代码开始 // 自动序列化,返回响应式 ref const userInfo = useStorage('userInfo', { id: 1, name: '张三' }) // 直接改值,自动写入 localStorage userInfo.value.name = '李四999977777' console.log("userInfo.value.name",userInfo.value.name) // 读取 localStorage 中的 userInfo const a = useStorage('userInfo', "") console.log("a.value",a.value) // 读取 localStorage 中的 userInfo 并解析为 JSON 对象 const userInfoJson = useStorage('userInfo', "") console.log("userInfoJson.value",userInfoJson.value) //删除 const clear = () => { userInfo.value = null } # 代码结束 封装工具函数:项目里可以封装 set / get / remove 方法,自动处理 JSON 序列化,代码更干净。 用 VueUse 的 useStorage:装了 @vueuse/core 的话,useStorage 可以把存储变成响应式 ref,改值自动写入存储,取出来也是响应式的。 javascript import { useStorage } from '@vueuse/core' // 自动序列化,返回响应式 ref const userInfo = useStorage('userInfo', { id: 1, name: '张三' }) // 直接改值,自动写入 localStorage userInfo.value.name = '李四' 需要响应式更新:如果希望多个组件同步 localStorage 的变化,可以结合 watch 或监听 storage 事件实现。 localStorage 的使用细节不少,可以继续了解JSON.stringify 会处理循环引用吗?或者storage 事件如何监听本地存储变化?监听响应式变量变化,自动保存到localStorage
// 监听响应式变量变化,自动保存到localStorage watchEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(storedValue.value)); } catch (error) { console.warn(`Error setting localStorage key “${key}”:`, error); } }); ———————————————— 版权声明:本文为CSDN博主「繁若华尘」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_41504401/article/details/145624397【Vue3】使用mitt实现任意组件通信
安装:【Vue3】使用mitt实现任意组件通信_vue3 mitt-CSDN博客
npm install mitt
常用API mitt().on() 绑定事件 mitt().emit() 触发事件 mitt().off() 卸载某个事件 mitt().all.clear() 卸载全部事件 使用方式一:封装模块暴露 步骤一 封装到utils工具箱中,对外暴露一个mitt实例 import mitt from 'mitt' const emitter = mitt() export default emitter; // 注意事项: // 引用 mitt 库 import mitt from 'mitt' // 先触发事件,再绑定事件,最后再解绑事件,再触发事件,结果是: 1 2 1 2 // 调用mitt()方法返回emitter,emitter可以:绑定事件、触发事件 // emitter.on('event', (data) => console.log(data)) // 绑定事件 // emitter.emit('event', { a: 1, b: 2 }) // 触发事件 // emitter.off('event') // 解绑事件 event 就是事件名 key // emitter.emit('event', { a: 1, b: 2 }) // 触发事件 // emitter.emit('event', { a: 1, b: 2 }) // 触发事件 // 调用 emitter 对象 const emitter = mitt(); // 导出 emitter 对象 // 暴露 emitter 对象 export default emitter ———————————————— 版权声明:本文为CSDN博主「心潮的滴滴」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_42582773/article/details/139692216vue3使用mitt 实现组件之间通信 (不限制组件之间关系)vue3使用mitt 实现组件之间通信 (不限制组件之间关系)iy
https://blog.51cto.com/u_12986423/13634117
Vue3一兄弟组件传值之mitt,超详细!mitt 挂载全局
// vue3挂载到全局
app.config.globalProperties.$mitt = mitt();
Vue3一兄弟组件传值之mitt,超详细!_vue3 mitt-CSDN博客
【Vue3】使用mitt实现任意组件通信_vue3 mitt-CSDN博客
vue3中事件总线mitt(第三方库mitt)_vue3 mitt-CSDN博客
Vue3 使用 mitt 实现跨组件通信-腾讯云开发者社区-腾讯云
注意:
一定是先触发 后绑定:
function giveMoney(){
// 触发事件 send-money 就是事件名 key, 10000 是事件数据
emitter.emit('send-money', [1,3,5,7,9,11,13,15]); // 值可以是任意类型 数字、字符串、对象、数组等 布尔值等
}
// 第二步绑定:
// 重点:接收数据方一定是绑定事件 // 事件名 send-money 是事件名 key, 事件数据 data 是事件数据. 对事件的绑定 import { onUnmounted, ref } from 'vue'; import emitter from '../../utils/emitter'; // 数据 const money = ref([]); function receiveMoney(data:number){ money.value = data; console.log(data) } // 绑定事件 // emitter.on('send-money', receiveMoney); // 绑定事件 // 事件名 send-money 是事件名 key, 事件数据 data 是事件数据 就是对应的 value. 对事件的绑定 emitter.on('send-money', (value:any[])=>{ // 事件数据 data 是事件数据 就是对应的 value. money.value = value; }); // 组件卸载时建议解除事件绑定。 // 避免内存泄漏 send-money 就是事件名 key onUnmounted(() => { emitter.off('send-money'); }); // 组件卸载时建议解除事件绑定。 // onUnmounted(() => { // emitter.off('send-money'); // });组件A中 引入mitt并使用emit发送数据
const data = ref('hello mitt'); import mitt from './mitt'; mitt.emit('data', data);组件B中 引入mitt并使用on接受数据
import mitt from './mitt'; mitt.on('data', (data)=>{ console.log(`inject this data ${ data }`) }); //inject this data hello mitt使用map,动态添加对象属性名,属性值
// 将map转为对象 function MapchangeToObj(strMap: any) { let obj = {}; for (let [key, val] of strMap) { obj[key] = val; } return obj; } let arrmap: any = new Map(); arrmap.set('test', 123); MapchangeToObj.(arrmap) // { test:123 }vue3 mitt可以完成任意组件之间的通信 完整事例
1. 安装 mitt bash npm install mitt 🔧 2. 创建事件总线(核心) 在 src/utils/eventBus.js 中创建并导出一个 mitt 实例,整个项目共用这一个实例: javascript import mitt from 'mitt' const emitter = mitt() export default emitter 🚀 3. 在组件中使用 假设有两个兄弟组件 ChildA.vue 和 ChildB.vue,ChildA 点击按钮把消息传给 ChildB。 ChildA.vue(发送方) vue <template> <div> <h3>组件 A</h3> <button @click="sendMessage">发送消息给 B</button> </div> </template> <script setup> import emitter from '@/utils/eventBus' const sendMessage = () => { emitter.emit('message-from-a', { text: '你好,我是组件 A!' }) } </script> ChildB.vue(接收方) vue <template> <div> <h3>组件 B</h3> <p>收到消息:{{ receivedMessage }}</p> </div> </template> <script setup> import { ref, onMounted, onUnmounted } from 'vue' import emitter from '@/utils/eventBus' const receivedMessage = ref('') const handleMessage = (data) => { receivedMessage.value = data.text } onMounted(() => { emitter.on('message-from-a', handleMessage) }) // 组件销毁时一定要解绑,避免内存泄漏 onUnmounted(() => { emitter.off('message-from-a', handleMessage) }) </script> ⚠️ 关键注意点 事件名要一致:emit 和 on 的事件名必须完全相同,且区分大小写。 记得解绑:接收方组件在 onUnmounted 中调用 off 解绑,否则会内存泄漏、事件重复触发。 单例使用:全局只创建一个 mitt 实例,不要在每个组件里新建,否则无法通信。 适合场景:mitt 适合轻量、瞬时的事件通知,比如“刷新列表”“关闭弹窗”;如果是复杂状态管理,还是用 Pinia 更合适。骖