状态管理Pinia
可以看作是一个公共的域对象
首先,安装Pinia:
npm install pinia
在Vue.js应用程序中,创建一个Pinia store。这是一个存储应用程序状态的地方。可以在其中定义状态、操作和获取器。
// store.js
/*定义共享的pinia数据*/
import { defineStore } from 'pinia';
//定义一个Person共享
export const useStore = defineStore({
id: 'main',//当前数据的id必须全局唯一
state: () => ({//状态,其实就是响应式数据
count: 0,
}),
actions: {//专门定义一些修改数据的函数
increment() {
this.count++;
},
},
getters: {//专门定义获得数据或者是使用数据计算结果的函数
doubleCount() {
return this.count * 2;
},
},
});
在Vue组件中使用这个store:
<template>
<div>
<p>Count: {{ $store.count }}</p>
<p>Double Count: {{ $store.doubleCount }}</p>
<button @click="$store.increment()">Increment</button>
</div>
</template>
<script>
import { useStore } from './store';
export default {
setup() {
const store = useStore();
return { $store: store };
},
};
</script>
最后,在Vue应用程序的入口文件中,将Pinia添加到Vue实例中:
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';
const app = createApp(App);
app.use(createPinia());
app.mount('#app');