Pinia学习总结

Pinia学习链接: pinia.vuejs.org/

1、含义

Pinia是一个简单使用的状态管理工具,为vue应用程序提供共享状态管理能力。

2、特点:

  • 语法和vue3一样,有2种语法:选项式API和组合式API
  • 可以创建多个全局仓库,不像Vuex一个仓库嵌套模块,结构复杂
  • 管理数据简单,提供数据和修改数据的逻辑即可,不像vuex需要记忆太多的API。

3、使用步骤

// 安装
npm i pinia

// 导入,实例化,当作插件使用,和其他插件使用套路相同
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')


// 创建仓库&使用仓库
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const userCounterStore = defineStore('counter', () => {
    return {}
})


// vue中使用
import { userCounterStore } from './store/counter'
const store = userCounterStore()


// 进入状态管理

// state
const count = ref(100)

// getters
const doubleCount = computed(() => count.value * 2)

// mutations
const update = () => count.value++

// actions
const asyncUpdate = () => {
    setTimeout(() => {
        count.value++
    }, 1000)
}
return { count, doubleCount, update, asyncUpdate }


// 去使用
<template>
    App {{ store.count }} {{ store.doubleCount }}
    <button @click="store.update()">count++</button>
    <button @click="store.asyncUpdate">async update</button>
</template>

4、storeToRefs的使用

解决解构仓库状态丢失响应式的问题

    import { storeToRefs } from 'pinia'
    
    const store = useCounterStore()
    const { count, doubleCount } = storeToRefs(store)

5、Pinia和Vuex的区别

12.png