页面有搜索结果后,进入详情页后返回,保留搜索结果

VUE3 + Pinia + TS 列表页面有搜索结果后,进入详情页后返回,没有保留搜索结果,需要重新搜索 。用pinia咋实现呀

【相关推荐】



  • 看下这篇博客,也许你就懂了,链接:Vue3 - Pinia 状态管理(环境搭建安装及各属性使用教程)详细使用教程
  • 除此之外, 这篇博客: 分享 15 个 Vue3 全家桶开发的避坑经验中的 2. Pinia 修改数据状态的方式 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    按照官网给的方案,目前有三种方式修改:

    1. 通过 store.属性名赋值修改单笔数据的状态;

    这个方法就是前面一节使用的:

    const changeName = () => {
      componentStoreObj.name = 'hello pingan8787';
    }
    
    1. 通过 $patch方法修改多笔数据的状态;

    文档地址:

    https://pinia.vuejs.org/api/interfaces/pinia._StoreWithState.html#patch

    当我们需要同时修改多笔数据的状态时,如果还是按照上面方法,可能要这么写:

    const changeName = () => {
      componentStoreObj.name = 'hello pingan8787'
      componentStoreObj.age = '18'
      componentStoreObj.addr = 'xiamen'
    }
    

    上面这么写也没什么问题,但是 Pinia 官网已经说明,使用 $patch的效率会更高,性能更好,所以在修改多笔数据时,更推荐使用 $patch,使用方式也很简单:

    const changeName = () => {
      // 参数类型1:对象
      componentStoreObj.$patch({
        name: 'hello pingan8787',
        age: '18',
        addr: 'xiamen',
      })
      
      // 参数类型2:方法,该方法接收 store 中的 state 作为参数
      componentStoreObj.$patch(state => {
        state.name = 'hello pingan8787';
        state.age = '18';
        state.addr = 'xiamen';
      })
    }
    
    1. 通过 action方法修改多笔数据的状态;

    也可以在 store 中定义 actions 的一个方法来更新:

    // store.ts
    import { defineStore } from 'pinia';
    
    export default defineStore({
        id: 'testStore',
        state: () => {
            return {
                name: 'pingan8787',
                age: '10',
                addr: 'fujian'
            }
        },
        actions: {
            updateState(){
                this.name = 'hello pingan8787';
                this.age = '18';
                this.addr = 'xiamen';
            }
        }
    })
    
    

    使用时:

    const changeName = () => {
      componentStoreObj.updateState();
    }
    

    这三种方式都能更新 Pinia 中 store 的数据状态。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^