vue mixins的使用
刚开始接触vue的时候,官网关于mixins的例子看了好几遍,发现还是不会用,包括vuex也是后来慢慢理解一点的,不过和vuex比起来。mixns还是很好理解,简单很多了
就我目前理解mixns,它就相当于一个中间件,可以把一些公用的函数,方法放到这个中间件,页面调用的时候只需要引入mixns就行,提高重复利用率
以存储城市历史记录为例:
1. 在src目录下新建mixns目录,下面新建文件getHistoryCity.js
export default{ methods:{ setCitys(data){
let searchCity = sessionStorage.getItem('CITY_INFO');
if(!searchCity){//如果没有历史记录
let option=[];
option.push(data);
sessionStorage.setItem(storename,JSON.stringify(option));
}else{
let newSearchCity=JSON.parse(searchCity);
if(newSearchCity.indexOf(data)==-1){ // 如果数组中没有,就加进去,最多存9条
newSearchCity.push(data)
if(newSearchCity.length>9){
newSearchCity.splice(1,newSearchCity.length)
}
}
sessionStorage.setItem(storename,JSON.stringify(newSearchCity));
}
},
getCitys(){
return JSON.parse(sessionStorage.getItem('CITY_INFO'));
}
}
}
组件或页面里调用 index.vue
<template> <div class="his_wrap" v-if="historycitys"> <div class="tit">历史选择城市</div> <div class="flex-wrap"> <div class="his_city" v-for="item in historycitys">{{item}} </div> </div> </div> </template> <script> import historyCityMixin from '@/mixins/getHistoryCity' export default { name:'index', mixins:[historyCityMixin], data(){ return{ historycitys:null } }, created(){ this.historycitys = this.getgetCitys(); }, methods:{ selectCity(item){ this.setCitys(item) } } } </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误