场景:地区选择器中,由于方法很长,加载的数据很多,导致页面每进去一次都要加载很久,造成页面卡顿。所以想要把这个数据和方法,提到外面,得到的数据,供所有页面都能正常使用。
使用pinia:
1.main.ts中
import { createPinia } from 'pinia'
2.stores/area.js
import { defineStore } from 'pinia'
import mapData from '../assets/mapData/area.json';
export const useArea = defineStore({
id: 'area',
state: () => {
return {
// navInfo: []
province: [],
cities : [],
counties : []
}
},
getters: {
},
actions: {
getCityData(){
var that = this
// var data = mapData
that.province = []
that.cities = []
that.counties = []
for (var item in mapData) {
if (item.match(/0000$/)) {
//省
this.province.push({ id: item, value: mapData[item], children: [] });
} else if (item.match(/00$/)) {
//市
this.cities.push({ id: item, value: mapData[item], children: [] });
} else {
//区
this.counties.push({ id: item, value: mapData[item] });
}
}
// 分类市级
for (var index in this.province) {
for (var index1 in this.cities) {
if (
this.province[index].id.slice(0, 2) ===
this.cities[index1].id.slice(0, 2)
) {
this.province[index].children.push(this.cities[index1]);
}
}
}
// 分类区级
for (var item1 in this.cities) {
for (var item2 in this.counties) {
if (
this.counties[item2].id.slice(0, 4) ===
this.cities[item1].id.slice(0, 4)
) {
this.cities[item1].children.push(this.counties[item2]);
}
}
}
},
}
})
3.页面中正常使用。(如果想要数据不互相影响,那就注释,如果想要共享,那就打开注释的代码。)
// import { storeToRefs } from "pinia";
import { useArea } from "@/stores/area";
const areaStore = useArea();
// const { province,cities,counties } = storeToRefs(areaStore);
import mapData from "@/assets/mapData/area.json"
province:areaStore.province,
cities: areaStore.cities,
counties: areaStore.counties,
pinia相关的一篇链接:(69条消息) Vue3-Pinia的基本使用_blackzjj的博客-CSDN博客_vue3 pinia