VUE3 + Pinia + TS 列表页面有搜索结果后,进入详情页后返回,没有保留搜索结果,需要重新搜索 。用pinia咋实现呀
【相关推荐】
按照官网给的方案,目前有三种方式修改:
store.属性名
赋值修改单笔数据的状态;这个方法就是前面一节使用的:
const changeName = () => {
componentStoreObj.name = 'hello pingan8787';
}
$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';
})
}
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 的数据状态。