Vue pinia 基础使用


theme: smartblue

一、环境搭建

1.1 安装

npm i pinia

image.png

1.2 引用

image.png

``` import { createApp } from 'vue' import './style.css' import App from './App.vue' import { createPinia } from 'pinia' const store =createPinia()

export const app = createApp(App)

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

```

二、简单使用

2.1 初始化

创建枚举类 store-name.ts

export const enum Names { TEST = "TEST" }

创建 store

``` import {defineStore} from 'pinia' import {Names} from "./store-name"

export const useTestStore = defineStore(Names.TEST,{ state:()=>{ return { current:1, name:'xyy' } }, // 类似于computed,有缓存 getters:{

},
// 类似于 methods,可以做同步、异步、提交
actions:{

}

}) ```

2.2 使用

``` {{ Test.current }} --- {{ Test.name }}

```

image.png

三、修改 store 值

3.1 直接修改

``` {{ Test.current }} --- {{ Test.name }}

```

20231126_164316.gif

3.2 $patch 批量修改

``` {{ Test.current }} --- {{ Test.name }}

```

20231126_164628.gif

3.3 $patch 函数处理

``` {{ Test.current }} --- {{ Test.name }}

```

20231126_164938.gif

3.4 $state 批量修改

``` {{ Test.current }} --- {{ Test.name }}

```

20231126_165310.gif

3.5 action

在 store 中的action 添加修改逻辑

``` import {defineStore} from 'pinia' import {Names} from "./store-name"

export const useTestStore = defineStore(Names.TEST,{ state:()=>{ return { current:1, name:'xyy' } }, // 类似于computed,有缓存 getters:{

},
// 类似于 methods,可以做同步、异步、提交
actions:{
   setCurrent(){
    this.current = 555
   }
}

}) ``` 使用定义好的函数方法

``` {{ Test.current }} --- {{ Test.name }}

```

20231126_165640.gif

四、 解构 store

4.1 基础使用

``` {{ Test.current }} --- {{ Test.name }}

```

image.png

4.2 常见问题

注意:pinia解构不具有响应式

20231126_170518.gif

解决策略:使用storeToRefs

image.png

``` {{ Test.current }} --- {{ Test.name }}

```

20231126_170849.gif

五、actions

5.1 简单使用

在 store 中的 actions 中为 user 赋值

``` import {defineStore} from 'pinia' import {Names} from "./store-name"

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

let result:User = { name:'xyy', age:23 }

export const useTestStore = defineStore(Names.TEST,{ state:()=>{ return { user: {}, name:'' } }, // 类似于computed,有缓存 getters:{

},
// 类似于 methods,可以做同步、异步、提交
actions:{
   setUser(){
    this.user = result
   }
}

}) ```

调用初始化方法

``` {{ Test }}

```

效果如下:

20231126_172309.gif

5.2 调用异步方法

``` import {defineStore} from 'pinia' import {Names} from "./store-name"

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

let result:User = { name:'xyy', age:23 }

const login = ():Promise =>{ return new Promise((resolve)=>{ setTimeout(()=>{ resolve({ name:'zhangsan', age:33 }) },2000) }) }

export const useTestStore = defineStore(Names.TEST,{ state:()=>{ return { user: {}, name:'' } }, // 类似于computed,有缓存 getters:{

},
// 类似于 methods,可以做同步、异步、提交
actions:{
   async setUser(){
     this.user = await login()
   }
}

}) ```

image.png

20231126_172807.gif

六、getter

6.1 简单使用

定义 getter 内容

image.png

获取 getter 内容

image.png

image.png

getters 也可以调用同类方法

image.png

20231126_174152.gif

七、api调用

7.1 $reset

作用:重置 store 到他的初始值

image.png

20231126_192604.gif

7.1 $subscribe

作用:监听器,观察的store有变化时,就会走这个函数

image.png

20231126_193101.gif

7.2 $onAction

监听 action 中方法

image.png

image.png

此外,还接受一个参数 true,作用为当组件销毁之后,还继续监听这个事件

image.png

八、pinia 持久化插件

8.1 现有问题

当页面刷新后,pinia的状态都会丢失

20231126_194048.gif

8.2 解决过程

在main.ts中,注册自定义store插件

``` import { createApp,toRaw } from 'vue' import './style.css' import App from './App.vue' import { createPinia,PiniaPluginContext } from 'pinia' const store =createPinia()

const setStorage = (key:string,value:string)=>{ localStorage.setItem(key,JSON.stringify(value)) }

const getStorage = (key:string)=>{ return localStorage.getItem(key)?JSON.parse(localStorage.getItem(key) as string) : {} }

type Options = { key?:string }

const piniaKey:string = 'defaultKey'

const piniaPlugin = (options:Options) =>{

return (context:PiniaPluginContext) =>{
    const {store} = context
    const data = getStorage(`${options?.key??__piniaKey__}-${store.$id}`)
    console.log(data)

    store.$subscribe(()=>{
        console.log(toRaw(store.$state))
        setStorage(`${options?.key??__piniaKey__}-${store.$id}`,toRaw(store.$state))
    })

    return {
        ...data
    }
}

} store.use(piniaPlugin({ key:'pinia' }))

export const app = createApp(App)

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

```

20231126_200803.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值