前情提要:主页面有个日期选择框,选择某个日期之后,从主页面点击超链接跳转到其他页面再返回的时候,日期又回到初始值而不是我选择的那个值,这就涉及到属性的状态管理即vuex,也是我们常说的store
关于vuex我这里不再赘述,感兴趣的小伙伴建议去官网了解:https://vuex.vuejs.org/zh/
针对上述具体的场景我们来简单实现一下参数状态的共享与同步:
- 定义store库
创建一个store.ts文件,在里面写入以下内容:
import { defineStore } from 'pinia';
export const Store = defineStore({
id: 'Store', //为状态存储指定一个唯一的标识符
// 定义我们要共享状态属性,info_date通过store实现在各个页面的共用
state: () => ({
info_date:new Date()
}),
// 在getters里面定义获取相关状态属性的方法
getters:{
getInfoDate(): any {
return this.info_date;
},
},
// 在actions里面提交我们的状态变更
actions: {
setInfoDate(value: any): any {
this.info_date = value;
},
},
});
- 主页面设置日期
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Store } from './store'; //引入我们定义的store
const theStore = Store(); // 创建store对象
// monthValue是日期框绑定的值
const monthValue = ref(theStore.info_date); // 获取store里面的info_date的值,作为monthValue的初始化值
// 监控monthValue值的变化,同步更新store里面info_date的状态
watch(monthValue,(newValue)=>{
theStore.setInfoDate(newValue); //newValue是日期框选择的值,我们赋给store里面的info_date,这样其他页面获取的info_date是这里更新之后的值,达到了info_date共享的目的
})
</script>
注:
- store里面属性的使用如上述所见:
store对象.属性
,比如theStore.info_date,其他页面使用同理 - store里面属性的状态更新如上述所示:
theStore.setInfoDate(新值)
,其他页面更新同理