pinia使用

本文介绍了如何在Vue项目中安装和使用Pinia状态管理库,包括引入、创建store、定义状态、getter、actions以及如何通过事件、$patch方法和storeRef实现响应式更新。
摘要由CSDN通过智能技术生成

安装pinia

npm install pinia

// 或者
yarn add pinia
  • 在项目中使用,先main.ts引用进来
import { createPinia } from 'pinia'

const pinia = createPinia()

app.use(pinia) // 即可,省略了部分代码
  • Sotre文件夹中书写index.ts
import { defineStore } from 'pinia'
// 定义一个设置命名空间的文件
import { Names } from './store-name'
/**
 * defineStore 有两个参数
 * 第一个参数:命名空间
 * 第二个参数:对值的操作,有state,getter,actions方法
 */
// 命名规则:hook都是以use开头
export const useTestStore = defineStore(Names.TEST,{
    state:()=>{
        return {
            current: 1,
            name: 'yx'
        }
    },
    // 类似于computed 修饰一些值
    getters:{

    },
    // methods:同步,异步方法都可以做,修改state
    actions:{

    }
})
  • store-name.js 枚举文件
export const enum Names {
    TEST = 'TEST'
}
  • App.vue 中使用
<template>
  <div>
    pinia:{{test.name}}
  </div>
</template>

<script setup lang="ts">

import { useTestStore } from './stores'

const test = useTestStore()

</script>
  • 修改state的五种方法
  1. 通过事件方法直接修改test里面的属性

<template>
  <div>
    pinia:{{test.name}}
  </div>
  <button @click="changeTest"> change</button>
</template>

<script setup lang="ts">

import { useTestStore } from './stores'

const test = useTestStore()
// 通过事件,直接修改test里面的之
const changeTest = ()=>{
  test.name = '我被改变了'
}

</script>

<style lang="scss" scoped>
</style>

  1. 通过pinia提供的$patch方法,可批量修改属性
const changeTest = ()=>{
  test.$patch({
    current: 44444,
    name:'hello'
  })
}
  1. 还是通过$patch,只不过里面传递的是函数写法
const changeTest = ()=>{
  // state 是 store里面定义的变量
  test.$patch((state)=>{
   // 在函数里面可以定义一些逻辑
   state.name = '你你你'
  })
}
  1. 使用$state 方法,但要修改state里面所有的值才行,不建议使用
const changeTest = ()=>{
  test.$state = {
    name: 'hao de',
    current: 222
  }
}
  1. 通过 actions 里面的方法,进行修改state
// methods:同步,异步方法都可以做,修改state
    actions:{
        // 因为需要使用this,所以这里不能用箭头函数,否则会改变this指向
        setCurrent (num:number = 999){
            this.current = num
        }
    }

// app.vue  里直接调用此方法即可

import { useTestStore } from './stores'

const test = useTestStore()

const changeTest = ()=>{
  test.setCurrent(888)
}
  • 获取的test值是可以进行结构的,但不具备响应式,因此使用storeRefs方法让其具备响应式
import { useTestStore } from './stores'

import { storeToRefs } from 'pinia'

const test = useTestStore()
// 结构 test 值,并让其具有响应式
const {current,name} = storeToRefs(test)

const changeTest = ()=>{
  current.value++
  name.value = '我被改变了'
}
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值