Vue 的使用入門
- Pinia摘要
State:一樣管理應用的狀態,但使用 defineStore 函數來定義。 Actions:與 state 同級,並且不再需要額外的 mutation。 Getters:用來派生狀態,也使用內建的 getters。
- #0 安裝 Pinia:termial
npm install pinia
- #1 創建一個 Pinia Store:store/index.js
import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), actions: { increment() { this.count++; }, }, getters: { doubleCount: (state) => state.count * 2, }, });
- #2 在主 Vue 實例中使用 Pinia Store: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');
- #3 從 Store 相關設置:compoted 變更 count
import { useCounterStore } from './store'; export default { computed: { count() { const store = useCounterStore(); return store.count; }, }, };
提交 actionmethods: { increment() { const store = useCounterStore(); store.increment(); }, },
使用 getterscomputed: { doubleCount() { const store = useCounterStore(); return store.doubleCount; }, },