Pinia官方文档
选项式api
javascript
/*
* @Author: Jackie
* @Date: 2023-06-25 09:58:10
* @LastEditTime: 2023-07-24 17:32:25
* @LastEditors: Jackie
* @Description: pinia
* @FilePath: /vue3-demo-pinia/src/store/counter.js
* @version:
*/
import { defineStore, storeToRefs } from 'pinia';
// 访问user store中数据
import { useUserStore } from './user';
// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
// export const useCounterStore = defineStore({id:'counter', state:()=> ({ count: 0 })},...)
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0, name: 'jackie' }),
getters: {
double: (state) => state.count * 2,
userNum: () => {
// 获取counter store中数据
const userSrote = useUserStore();
const { num } = storeToRefs(userSrote);
return num.value + '个';
}
},
actions: {
increment() {
this.count++;
}
},
persist: {
enabled: true, // 开启缓存 默认会存储在本地localstorage
storage: sessionStorage, // 缓存使用方式
paths: [] // 需要缓存键
// strategies: [ //自定义key和存储方式
// {
// key: 'indexStore',
// storage: localStorage //可以选择对应的存储形式(localStorage或者sessionStroage)
// }
// ]
}
});
// 你可以认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。
// 可以将状态重置为初始值 $reset()
// store.$reset()
// 可以替换store $state
// store.$state = { name: "℃", age: 22 }
// 使用订阅机制subscribe来实现数据的持久化存储 $subscribe
// store.$subscribe((mutation, state) => {
// localStorage.setItem(store.$id, JSON.stringify(state));
// });
组合式api
javascript
/*
* @Author: Jackie
* @Date: 2023-07-24 16:34:03
* @LastEditTime: 2023-07-24 17:07:20
* @LastEditors: Jackie
* @Description: user pinia
* @FilePath: /vue3-demo-pinia/src/store/user.js
* @version:
*/
import { defineStore, storeToRefs } from 'pinia';
import { toRefs, ref, reactive, computed } from 'vue';
// 访问counter store数据
import { useCounterStore } from './counter';
export const useUserStore = defineStore(
'user',
() => {
// 状态
const state = reactive({
name: 'jackie',
age: 18
});
const num = ref(0);
// 计算
const fullName = () => state.name + '' + state.age;
const Age = computed(() => `年龄:${state.age}-${num.value}岁`);
// 获取counter store中数据
const counterSrote = useCounterStore();
const { count } = storeToRefs(counterSrote);
const userCount = computed(() => count);
// 修改
const setName = (name) => (state.name = name);
const setAge = (age) => (state.age += age);
const addNum = () => (num.value += 1);
return {
...toRefs(state),
num,
fullName,
Age,
setName,
setAge,
addNum,
userCount
};
},
{
persist: {
enabled: true, // 开启缓存 默认会存储在本地localstorage
storage: sessionStorage, // 缓存使用方式
paths: [] // 需要缓存键
// strategies: [ //自定义key和存储方式
// {
// key: 'indexStore',
// storage: localStorage //可以选择对应的存储形式(localStorage或者sessionStroage)
// }
// ]
}
}
);
demo使用
javascript
<!--
* @Author: Jackie
* @Date: 2023-06-25 09:58:10
* @LastEditTime: 2023-07-24 17:39:12
* @LastEditors: Jackie
* @Description: file content
* @FilePath: /vue3-demo-pinia/src/views/HomeView.vue
* @version:
-->
<template>
<div class="home">
<h1>This is an home page</h1>
<p>{{ store.count }}</p>
<p>{{ count }}</p>
<p>Double count is {{ store.double }}-{{ store.userNum }}</p>
<p>{{ store }}</p>
<!-- <p>{{ store.increment }}</p>
<p>{{ increment }}</p> -->
<button @click="store.increment">store.Increment</button>
<hr />
<p>
{{ name }}-{{ age }}-{{ num }}-{{ userStore.fullName() }}-{{
userStore.Age
}}-{{ userStore.userCount }}
</p>
<button @click="userStore.setName('dyh')">setName</button>
<button @click="userStore.setAge(1)">setAge</button>
<button @click="userStore.addNum()">addNum</button>
<p>{{ userStore }}</p>
<button @click="reset">重置</button>
<button @click="setName">设置</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/store/counter';
import { useUserStore } from '@/store/user';
const store = useCounterStore();
const userStore = useUserStore();
// const { count } = store; //失去了响应式
const { count } = storeToRefs(store);
const { name, age, num } = storeToRefs(userStore);
// 批量设置
const setName = () => {
store.$patch({ name: 'dyh', count: 1000 });
userStore.$patch({ name: 'dyh', age: 1000 });
};
const reset = () => {
store.$reset();
userStore.$reset(); //默认setup语法不支持 在main.js中进行配置
};
onMounted(() => {
console.log(count);
console.log(name.value, age.value, num.value);
});
</script>
解决setup语法下不支持 .$reset() 方法的问题
javascript
/*
* @Author: Jackie
* @Date: 2023-06-25 09:58:10
* @LastEditTime: 2023-07-24 17:38:44
* @LastEditors: Jackie
* @Description: pinia
* @FilePath: /vue3-demo-pinia/src/main.js
* @version:
*/
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { createPinia } from 'pinia';
const pinia = createPinia();
// 为了解决setup语法下不支持 .$reset() 方法的问题
pinia.use(({ store }) => {
const initialState = JSON.parse(JSON.stringify(store.$state));
store.$reset = () => {
store.$state = JSON.parse(JSON.stringify(initialState));
};
});
// 数据持久化
import piniaPluginPersist from 'pinia-plugin-persist';
pinia.use(piniaPluginPersist);
createApp(App).use(pinia).use(router).mount('#app');