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文件
pinia的使用
count : {{ counter.count }}
doubleCount : {{ counter.doubleCount }}
name: {{ MStoreObj.name }} age : {{ MStoreObj.age }}
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;
}
}
})