不得不说,这个小菠萝很可爱呢
文档
npm: https://www.npmjs.com/package/pinia
github: https://github.com/vuejs/pinia
安装
npm i pinia
示例
官网的文档,写的不是很清楚,有一些代码被省略了,对新手来说还是很坑的,我折腾了两天,第一个Demo算是run起来了。
平时习惯使用Vue2的options方式,所以以下示例,就以options API方式实现。
本示例环境及其版本号
package.json
{ "name": "pinia-demo", "version": "1.0.0", "scripts": { "dev": "vite", "build": "vite build", "serve": "vite preview" }, "dependencies": { "pinia": "^2.0.8", "vue": "^3.2.13", }, "devDependencies": { "@vitejs/plugin-vue": "^2.0.1", "vite": "^2.4.1" }, "engines": { "node": ">=12.22.6", "npm": ">=6.14.15" } }
在Vue中使用Pinia
// src/main.js import { createApp } from 'vue'; import { createPinia } from 'pinia' const app = createApp(App); app.use(createPinia())
定义store
// src/stores/counter.js import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { // 数据 data state: () => { return { count: 0 } }, // 计算属性 computed getters: { // 访问store的数据 doubleCount: (state) => state.counter * 2, // 访问getters的数据 doublePlusOne() { return this.doubleCount + 1 }, }, // 修改数据的方法 methods actions: { increment() { this.count++ }, }, })
使用store
// src/components/Index.vue import { mapState, mapActions } from 'pinia' import { useCounterStore } from '@/stores/counter.js' export default { computed: { ...mapState(useCounterStore, ['counter', 'doubleCount']) }, methods: { ...mapActions(useCounterStore, ['increment']) } }