用pinia和<KeepAlive>时需要注意Cache被改写的问题
用了pinia做状态管理,如果代码写的不当,遇到 <KeepAlive>时容易造成Cache被改写的问题
computed: { ...mapWritableState(useGoodsStore, { _listData: 'items', _isListEnd: 'isListEnd', _max: 'maxPage', }),
如果在template里直接把 _listData作为页面的data,例如下面的router component Index.vue 和父级MainLayout.vue
<q-list separator dense class="bg-secondary" id="scroll-target-id"> <div id="containerId" v-bind:key="item.id" v-for="item in _listData" class="bg-primary" v-bind:class="{ 'q-pb-sm': !isBigScreen }" >
<router-view v-slot="{ Component }"> <KeepAlive> <component :is="Component" :key="$route.fullPath" :sort="sortIndex" ref="goods-list" /> </KeepAlive> </router-view>
router.js
path: '/', component: () => import('layouts/MainLayout.vue'), children: [ { path: '', meta: { isGoodsList: true }, components: { default: () => import('pages/Index.vue'), // hot: () => import('components/HotList.vue'), hot: () => import('components/ResourceSideList.vue'), }, props: { default: (route) => ({ sort: route.query.sort, }), hot: false, }, }, { path: 'list/:page', meta: { isGoodsList: true }, components: { default: () => import('pages/Index.vue'), // hot: () => import('components/HotList.vue'), hot: () => import('components/ResourceSideList.vue'), }, props: { default: (route) => ({ query: route.query.q, sort: route.query.sort }), hot: false, }, }, { path: ':path', meta: { isGoodsList: true }, components: { default: () => import('pages/Index.vue'), hot: () => import('components/ResourceSideList.vue'), }, props: { default: (route) => ({ query: route.query.q, page: route.query.page, sort: route.query.sort, }), hot: false, }, },
因为很多router都指向了Index.vue, 当有router1变成router2,例如从 'list/:page' 跳转到 ':path', 本来'list/:page' 的_listData已经被Cache,但到了':path',_listData的数据被改写,导致Cache里的数据也被改了。
正确的做法是在data里定义listData,页面的数据使用listData,在created()的hook里 this.listData = this._listData
<q-list separator dense class="bg-secondary" id="scroll-target-id"> <div id="containerId" v-bind:key="item.id" v-for="item in listData" class="bg-primary" v-bind:class="{ 'q-pb-sm': !isBigScreen }" >
data() { return { listData: [], max: 0, isListEnd: false, } computed: { ...mapWritableState(useGoodsStore, { _listData: 'items', _isListEnd: 'isListEnd', _max: 'maxPage', }), created() { console.log('Index created' + this.$route.fullPath); this.listData = this._listData; this.max = this._max; this.listEnd = this._listEnd; },
喜欢艺术的码农
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人