微信小程序pinia的应用
情景:院校列表的关注状态的实时更新
新建一个ts文件存储关注状态,用于集中管理用户“已关注院校”的相关状态和操作
import {definStore} from 'pinia';
import type { College_records } from '@/types/university';export const useFocusCollegeStore = defineStore('focusCollege',{
//定义一个响应式状态state:() => ({
//保存用户当前已关注的所有院校信息focusCollegeList: [] as College_records[],}),actions: {
//替换整个关注列表为新数组setFocusCollegeList(list: College_records[]) {this.focusCollegeList = list;},
// 向关注列表添加一个新的院校addFocusCollege(college: College_records) {this.focusCollegeList.push(college);},
//从列表移除某个院校removeFocusCollege(code: string) {this.focusCollegeList = this.focusCollegeList.filter(item => item.code !== code);},},
});
- 只展示已关注的院校列表
import { useFocusCollegeStore } from '@/stores/modules/useFocusCollegeStore';const focusCollegeStore = useFocusCollegeStore();const handleClickFocus = async (item:items) => {//....其它代码focusCollegeStore.removeFocusCollege(item.code); }
- 在展示所有院校的列表里同步关注状态
import { useFocusCollegeStore } from '@/stores/modules/useFocusCollegeStore';const focusCollegeStore = useFocusCollegeStore();//获取已关注院校的列表 const fetchFocusCollegeList = async() => {//....其他代码const response = await getFocusCollege();focusCollegeStore.focusCollegeList = response.items || [];console.log('已关注院校:', focusCollegeStore.focusCollegeList); }//根据已关注列表更新院校关注状态 const updateStatus = () =>{//...其他代码 focusList.value = focusList.value.map(item => {const isBookmarked = focusCollegeStore.focusCollegeList.some(focusItem => focusItem.code === item.code);return {...item,bookmark: isBookmarked}; };//监听store变化并自动更新 watch(() => focusCollegeStore.focusCollegeList,() => {updateBookmarkStatus();},{ deep: true } );