83 lines
1.4 KiB
JavaScript
83 lines
1.4 KiB
JavaScript
import {
|
|
ref,
|
|
reactive
|
|
} from 'vue';
|
|
import {
|
|
defineStore
|
|
} from 'pinia'
|
|
import {
|
|
parse,
|
|
stringify
|
|
} from 'zipson'
|
|
|
|
|
|
export const useCommon = defineStore(
|
|
'common',
|
|
() => {
|
|
const test = 'test'
|
|
return {
|
|
test
|
|
}
|
|
|
|
}, {
|
|
persist: {
|
|
paths: ['commonState'],
|
|
storage: {
|
|
getItem(key) {
|
|
return uni.getStorageSync(key)
|
|
},
|
|
setItem(key, value) {
|
|
uni.setStorageSync(key, value)
|
|
},
|
|
},
|
|
serializer: {
|
|
deserialize: parse,
|
|
serialize: stringify,
|
|
}
|
|
}
|
|
})
|
|
|
|
/*
|
|
页面内使用pinia
|
|
|
|
1、引用你定义的store实例
|
|
import { useUserStore } from '@/stores/user'
|
|
|
|
2、实例化useUserStore
|
|
const user = useUserStore()
|
|
|
|
3、引入 storeToRefs 用于 给实例的属性创建refs,即响应式
|
|
import { storeToRefs } from 'pinia'
|
|
例如:const {count} = storeToRefs(user)
|
|
count.value 此时为响应式
|
|
|
|
4、修改state 方式共两种 如下
|
|
user.count++
|
|
4-1、
|
|
// 带自动补全 ✨
|
|
user.$patch({ count: counter.count + 1 })
|
|
$patch()可批量修改state的属性值
|
|
例如:
|
|
批量修改
|
|
const pathState = () => {
|
|
store.$patch({
|
|
user: { name: 'ks', age: 20 },
|
|
});
|
|
};
|
|
|
|
其他操作state的方法如下:
|
|
|
|
替换State
|
|
const replaceState = () => {
|
|
store.$state.user = { age: 20, name: 'eee', sex: 'women' };
|
|
};
|
|
重置state的值
|
|
const reset = () => {
|
|
store.$reset();
|
|
};
|
|
|
|
4-2、
|
|
// 或使用 action 代替
|
|
user.increment()
|
|
|
|
*/ |