Pinia的使用

安装

yarn add pinia
# or
npm i pinia

基本使用

在main.js中挂载Pinia

import { createPinia } from 'pinia'
const Pinia = createPinia()

createApp(App).use(Pinia).mount('#app')

新建仓库文件

src/test.js

引入defineStore方法
import { defineStore } from 'pinia'
创建store

命名规则:useXxxStore

defineStore( storeID , {state,actions,getters} )

参数1:store的唯一标识,也就是仓库名字

参数2:对象,可以在对象内提供state、actions、getters

const useTestStore = defineStore('test', {
  // state是一个函数 在返回的对象中写数据
    state: () => {
        return {
            name: 'liao',
            website: 'https://liaooo.cn',
        }
    },
    actions: {},
    getters: {}
})

export default useTestStore
在组件中使用
<script setup>
    import useTestStore from './store/test'
    const test = useTestStore()
</script>

<template>
    {{ test.name }}
    {{ test.website }}
</template>

actions的使用

Pinia中没有mutations,只有actions

在actions中添加方法并修改数据

...
actions: {
        changeName(name) {
            this.name = name
        }
  }
...

在组件中使用actions

<script setup>
    import useTestStore from './store'
    const test = useTestStore()
  // 执行actions中的方法
    test.changeName('liaoliao')
</script>

getters的使用

添加getter

...
getters: {
        infoPage() {
            return this.website + '/talking'
        },
    }
...

在组件中使用

<template>
    ...
    {{ test.infoPage }}
</template>

<script setup>
    import useTestStore from './store'
    const test = useTestStore()
    ...
</script>

storeToRefs的使用

直接解构store中的数据会导致数据丢失响应式特性

<script setup>
    import useTestStore from './store'
    const test = useTestStore()
  // 解构出来的数据将不再是响应式的
    const { name, website } = test
    ...
</script>

使用storeToRefs可以使解构出来的数据依旧是响应式的

<script setup>
  // 从pinia中引入storeToRefs方法
  import { storeToRefs } from 'pinia'
    ...
    const { name, website } = storeToRefs(test)
    ...
</script>

模块化

根据项目复杂程度,有时候需要存储较多数据,可以定义多个store,最后统一用一个根store整合

新建user模块

src/store/user.js

import { defineStore } from 'pinia'

const useUserStore = defineStore('user', {})

export default useUserStore

新建······模块

新建根store

src/store/index.js

// 导入所有store
import useUserStore from './user'
import use···Store from './···'

// 统一导出useStore()方法
export default function useStore() {
  return {
    user: useUserStore(),
     ···: use···Store()
  }
}

在组件中使用

<script setup>
    import { storeToRefs } from 'pinia'
    import useStore from './store'
  // 解构user store
    const { user } = useStore()
    const { name, pwd } = storeToRefs(user)
</script>

订阅store中数据的变化($subscribe)

store.$subscribe详见下一篇笔记


已发布

分类

来自

标签:

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注