Pina官网 Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。
main.js文件
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
//import {storeReset} from './stores/counter'
const app = createApp(App)
const store = createPinia();
//reset使用是需要添加
//Uncaught Error: 🍍: Store "counter" is built using the setup syntax and does not implement $reset().
store.use(({store})=>{
const initialState = JSON.parse(JSON.stringify(store.$state));
store.$reset = ()=>{
store.$state = JSON.parse(JSON.stringify(initialState));
}
});
app.use(store)
app.mount('#app')
App.vue文件
<script setup>
import { storeToRefs } from "pinia"
import {useCounterStore} from './stores/counter'
import {MObj} from './stores/mystore'
import ChildA from './components/ChildA.vue';
storeToRefs(useCounterStore()) //响应处理,其他页面也会实时更新
const counter = useCounterStore();
const MStoreObj = MObj();
//订阅修改
counter.$subscribe((mutation, state)=>{
console.log("some value change");
console.log(mutation, state)
})
function add()
{
counter.count++;
}
function reset()
{
//counter.$state = {count:0};
counter.$reset();
}
function add_age()
{
MStoreObj.add_age(1);
}
function change_name()
{
console.log("2222");
MStoreObj.changename("new name ");
}
</script>
<template>
<h2>pinia的使用</h2>
<p> count : {{ counter.count }} </p>
<p> doubleCount : {{ counter.doubleCount }} </p>
<button @click="counter.increment">add func</button>
<button @click="add">add count</button>
<button @click="reset">reset count</button>
<br/>
<br/>
<div> name: {{ MStoreObj.name }} age : {{ MStoreObj.age }}</div>
<button @click="add_age">add age</button>
<button @click="change_name"> change_name</button>
<br/>
<ChildA></ChildA>
</template>
<style scoped>
</style>
counter.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
mystore.js文件
import { ref, computed } from 'vue'
import { defineStore, mapActions } from 'pinia'
export const MObj = defineStore("myobj",{
state : ()=>{
return {
name: "a",
age: 0
}
},
actions : {
add_age(num){
this.age+=num;
},
changename(newname)
{
this.name = newname;
}
}
})