多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[danger] ## 安装 ~~~ yarn add pinia # 或者使用 npm npm install pinia ~~~ >[success] # 使用 1. 先将`pinia` 注册到`vue` ~~~ import { createApp } from "vue"; import App from "./App.vue"; import { createPinia } from "pinia"; const pinia = createPinia(); const app = createApp(App); app.use(pinia); app.mount("#app"); ~~~ 2. 和`vuex `不同在于 `pinia` 是通过一个一个`Store`,一个 Store (如 Pinia)是一个实体里包含了,[state](https://pinia.web3doc.top/core-concepts/state.html)、[getters](https://pinia.web3doc.top/core-concepts/getters.html)和[actions](https://pinia.web3doc.top/core-concepts/actions.html) ![](https://img.kancloud.cn/58/2a/582a5a8320a6095633922d9349911bf7_579x314.png),保存了全局的状态,在你的应用程序中定义任意数量的Store来管理你的状态,使用`defineStore ` 注册数据store * id,是必要的,`Pinia `使用它来将 `store `连接到 `devtools`。 * options 一个对象,store的配置项,比如配置store内的数据,修改数据的方法等 * 返回的函数统一使用`useX`作为命名方案,这是约定的规范 ~~~ // \src\store\modules\users.js import { defineStore } from 'pinia' // 第一个参数是应用程序中 store 的唯一 id export const useUsersStore = defineStore('users', { // 其它配置项 state: () => ({ name: "ww", age: 12, }), }) ~~~ 3. 在页面直接使用注册`Store` 通过调用函数来使用 ~~~ <template> <div @click="changeName"> {{ usersStore.name }} </div> </template> <script setup> // 直接导入 defineStore 创建对应位置 store import { useUsersStore } from "@/store/modules/users"; // 使用创建的 defineStore 创建的 usersStore 函数 const usersStore = useUsersStore(); function changeName() { usersStore.name = "zz"; } console.log(usersStore); </script> ~~~ * 使用打印我们自己创建的 `useUsersStore ` ![](https://img.kancloud.cn/9b/05/9b0573263584481b2ac4454c16c04798_1004x315.png) >[danger] ##### 刚使用时候疑惑 如果定义了两个store,用同名属性该怎么办?实际`pinia ` 和`vuex` 在管理上不同,每一个store 是独立的,并不是像`vuex` 在一个根上会出现这种同名问题,正因为相对独立更加函数式编程 ![](https://img.kancloud.cn/58/2a/582a5a8320a6095633922d9349911bf7_579x314.png)