准备
https://blog.csdn.net/qq_36437991/article/details/134474050
安装pinia
官网
yarn add pinia
src下新建store文件夹,该文件夹下新建index.ts
import { createPinia } from "pinia";
const store = createPinia();
export default store;
修改main.ts
import { createApp } from "vue";
import App from "./App.vue";
import store from "./store/index";const app = createApp(App);
app.use(store);
app.mount("#app");
sotre下新建user.ts
import { defineStore } from "pinia";export const useUserStore = defineStore({id: "user", // id必填,且需要唯一state: () => {return {name: "张三",};},actions: {updateName(name: string) {this.name = name;},},
});
修改home.vue
<script lang="ts" setup>
import { useUserStore } from '../store/user'
const userStore = useUserStore()
const changeState = () => {userStore.updateName('李四')
}
</script>
<template><p>获取pinia数据</p><div>{{ userStore.name }}</div><button @click="changeState">修改state</button>
</template>