7、Vue 3 Pinia 使用实录:Pinia 功能扩展

作者: 温新

图书: 【Vue 3 Pinia 使用实录】

阅读: 182

时间: 2024-09-08 07:18:12

嗨,我是温新

pinia 可以使用插件为 store 扩展功能。也就是,可以使用插件功能扩展出额外的功能。

可以扩展的功能列表:

  • 向 Store 添加新属性
  • 定义 Store 时添加新选项
  • 为 Store 添加新方法
  • 包装现有方法
  • 更改甚至取消操作
  • 实现本地存储等副作用
  • 适用于特定 Store

扩展功能的基本使用

1、扩展功能
import { createApp } from 'vue'
import App from './App.vue'

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

// 扩展仓库功能
pinia.use(() => {
    return {
        webName:"王美丽的 Vlog"
    }
})


const app = createApp(App)
app.use(pinia)

app.mount('#app')
2、数据仓库

src/stores/info.ts

import { defineStore } from "pinia";

const useInfoStore = defineStore('info', () => {
        return Math.floor(Math.random() * 100)
    }

    return {
        getRandomNumber
    }
})
export default useInfoStore
3、使用扩展属性

src/App.vue

<template>
  <h3>Vue 3 Pinia 使用实录</h3>
  <div class="main">
		<h3>{{  infoStore.webName }}</h3>
  </div>
</template>

<script setup lang="ts">
	import  useInfoStore  from "@/stores/info.ts";

	const infoStore = useInfoStore()
</script>

<style scoped>
	.main {
	background-color: pink;
	}
</style>

通过扩展出来的属性或方法,在所有 state 中都可以使用。

扩展属性和方法

上面的案例对通过扩展属性来演示 Pinia 扩展的基础使用。除了扩展属性,还能扩展方法。

1、注册扩展方法

src/main.ts

import { createApp } from 'vue'
import App from './App.vue'

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

pinia.use(() => {
    return {
        webName:"王美丽的 Vlog",
        // 扩展方法 方式 1
        getRandom: () => {
            return Math.random()
        }
    }
})

//  扩展方法 方式 2
pinia.use(({store}) => {
    store.getRandomNumber = () => {
        return Math.ceil(Math.random() * 100)
    }
})

const app = createApp(App)
app.use(pinia)

app.mount('#app')
2、使用扩展方法

src/App.vue

<template>
  <h3>Vue 3 Pinia 使用实录</h3>
  <div class="main">
		<h3>{{  infoStore.webName }}</h3>
		<h3>{{ infoStore.getRandom() }}</h3>
		<h3>{{ infoStore.getRandomNumber() }}</h3>
  </div>
  
</template>

<script setup lang="ts">
	import  useInfoStore  from "@/stores/info.ts";

	const infoStore = useInfoStore()

</script>

<style scoped>
	.main {
	background-color: pink;
	}
</style>

功能重写

当使用组合式 API 时,重置功能无法使用,因为 setup 语法糖中没有 $reset。我们的解决方法就是使用插件功能重写 $reset()

main.ts

...
pinia.use(({store}) => {
    // 获取原始值
    const initialState = JSON.parse(JSON.stringify(store.$state))
    store.$reset = () => {
        // 重置原始使用
        store.$state = JSON.parse(JSON.stringify(initialState))
    }
})
...
请登录后再评论