从使用的角度来看基本和Vuex
一样,但是更加简单。
有四个常用的核心概念:State
、Getter
、Mutation
、Action
。没有了Mutation
且常用的只有:State
、Getters
、Actions
(同步、异步、都支持)。
1.Store
创建一个js/store.js
文件:在index.html
中使用:
:::: code-tabs
@tab js/store.js
1 2 3 4 5 6 7 8 9 10
| const { defineStore } = Pinia;
const useCounterStore = defineStore("counter", { state: () => ({ age: 10, name: "小蓝", }), getters: {}, actions: {}, });
|
@tab index.html
:collapsed-lines1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="./lib/vue.min.js"></script> <script src="./lib/vueDemi.js"></script> <script src="./lib/pinia.min.js"></script> <script src="./js/store.js"></script> </head> <body> <div id="app"> <h1>姓名: {{ store.name }}</h1> <h1>年龄: {{ store.age }}</h1> </div> <script type="module"> const { createApp } = Vue; const { createPinia } = Pinia; const app = Vue.createApp({ setup() { const store = useCounterStore(); return { store, }; }, }); app.use(createPinia()); app.mount("#app"); </script> </body> </html>
|
::::
运行效果:
:::: demo-wrapper no-padding
::: center

:::
::::
2.Getters
Getters可以理解为共享的计算属性,假如需要上面的小蓝的两年后年龄就可以使用Getters
。
:::: code-tabs
@tab js/store.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const { defineStore } = Pinia;
const useCounterStore = defineStore("counter", { state: () => ({ age: 10, name: "小蓝", }), getters: { twoYear: (state) => { return state.age + 2; }, }, actions: {}, });
|
@tab index.html
1 2 3 4 5
| <div id="app"> <h1>姓名: {{ store.name }}</h1> <h1>年龄: {{ store.age }}</h1> <h1>两年后年龄为: {{store.twoYear}}</h1> </div>
|
::::
3.Actions
如果想要修改原始数据,就需要使用Actions
。
:::: code-tabs
@tab js/store.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const { defineStore } = Pinia; const useCounterStore = defineStore("counter", { state: () => ({ age: 10, name: "小蓝", }), getters: { twoYear: (state) => { return state.age + 2; }, }, actions: { changeAge() { this.age++; }, }, });
|
@tab index.html
1 2 3 4 5 6
| <div id="app"> <h1>姓名: {{ store.name }}</h1> <h1>年龄: {{ store.age }}</h1> <h1>两年后年龄为: {{store.twoYear}}</h1> <button @click="store.changeAge()">年龄+1</button> </div>
|
::::