前端实习准备 — Vue状态管理相关(Pinia)

187 阅读1分钟

基本使用

1. 安装
npm install pinia

2. 创建pinia插件 -- createPinia()
// store/index.js
<script setup>
    import {createPinia} from 'pinia'    
    export default const pinia  = cratePinia()
</script>
// main.js
<script setup>
    import {createApp} from 'vue'
    import APP from './App.vue
    import pinia from '@/store/index'
    
    const app = createApp(App)
    app.use(pinia)  
    app.mount('#app')
</script>

3. 定义store -- defineStore('uniqueName',()=>{ return{}})
defineStore接收两个参数,uniqueName为独一无二的id,第二个参数是一个setup函数/option对象,返回你想暴露的全局状态。defineStore最终返回一个包含所有全局状态的reactive对象。
可以调用任意全局属性,就跟正常setup下编写的程序一样。
可以编写任意多的store。

// store/counter.js
(1)setup store 
<script setup>
    import {defineStore} from 'pinia'
    // defineStore的返回值命名最好以use开头以store结尾
    export const useCouterStore = defineStore('counter',()=>{
        const count = ref(0)  // state
        const doubleCount = computed(()=> count.value*2)  // getter
        function increment(){  // action
            count.value++
        }
        // setup方式需要自己创建重置state函数,选项式API自带
        function $reset(){
            count.value = 0
        }
        return {count,doubleCount,increment,$reset}
    })
</script>
(2)option store
<script setup>
    import {difineStore} from 'pinia'
    export const useCounterStore = defineStore('counter',{
        states:()=>({  // ref
            count:0,
        }),
        getters:{  // computed
            doubleCunt:(state)=>state.count*2
        },
        actions:{  // function
            increment(){
                this.count++
            }
        }
    })
</script>
同时,$dispatch,$state,$subscribe,$reset等方法optionStore专属。
$dispatch 用于调度异步action -- setupStore直接调用方法即可
$state 用于访问状态 -- setupStore直接访问返回的ref/reactive对象
$subscribe 用于监听 -- setupStore通过wacth监听响应式数据
$reset 用于重置state -- setupStore需要自己定义方法返回

4. 使用store
<script setup>
    import {storeToRefs} from 'pinia'
    import {useCounterStore} from '@/store/counter'
    // 不能直接对reactive解构其属性,会破坏响应性。defineProps返回的也是reactive,但是它在vue3.5中自动获取响应式了,与这个不一样。应直接使用counterStore.count获取响应式数据。
    const counterStore = userCounterStore() // reactive对象
    // 使用storeToRefs(storeName)解构reactive属性
    const {count,doubleCount} = storeToRefs(store)
    // 可以直接对reactive解构其方法
    const {increment} = store
    // 变更state
    counterStore.count++
</script>