Pinia的使用技巧

一、安装
npm install pinia
二、main.ts引入
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'

const app = createApp(App)
app.use(createPinia())
app.mount('#app')
三、定义参数
import { defineStore } from 'pinia'

type User = {
    name: string,
    age: number
}

const peo: User = {
    name: 'cqs',
    age: 23
}

const login = (): Promise => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(peo)
        }, 2000)
    })
}

export const useTestStore = defineStore('user', {
    state: () => {
        return {
            name: 'cqs',
            age: 23,
            user: {}
        }
    },
    getters: {
        getNewName():string {
            return `好名字:${this.name}-${this.getAge}`
        },
        getAge():number {
            return this.age
        }
    },
    actions: {
        setName(name: string) {
            this.name = name;
        },
        async setUser() {
            const user = await login()
            this.user = user
        }
    }
})


四、store使用

1.直接获取

2.通过storeToRefs 获取

3.$patch修改

4.直接修改

5.通过$state修改

五、回滚数据
六、监听数据变化
七、添加浏览器缓存,避免刷新页面数据消失

修改main.ts

import { createApp, toRaw } from 'vue'
import App from './App.vue'
import { createPinia, PiniaPluginContext } from 'pinia'

const app = createApp(App)

type Option = {
    key: string
}

const PiniaPlugin = (option: Option) => {
    return (context: PiniaPluginContext) => {
        const { store } = context;
        const data = localStorage.getItem('pinia-' + option.key + store.$id);
        store.$subscribe(() => {
            localStorage.setItem('pinia-' + option.key + store.$id, JSON.stringify(toRaw(store.$state)))
        })
        return {
            ...(data ? JSON.parse(data) : {})
        }
    }
}

const store = createPinia();
store.use(PiniaPlugin({ key: 'cqs' }))
app.use(store)
app.mount('#app')

你可能感兴趣的:(Vue,javascript,开发语言,vue.js)