一、简易了解pinia(什么是pinia,pinia是干什么的)

Pinia是基于vuex创建的状态管理工具,真对vue3而开发,同时适用于vue3与vue2,支持js与ts编写,功能更优于vuex。
Pinia可通过插件对状态进行持久化存储,不会因为页面刷新而导致状态初始化。

二、下载pinia

yarn add pinia

三、pinia的使用

1.main.js全局注册pinia

在这里插入图片描述

引入:import { createPinia} from 'pinia'
注册:const pinia = ceatpinia;

2.创建store(defineStore)

import { defineStore } from 'pinia'

defineStore:传入二个参数:1.”id”类似于Store名字。2.对象函数
内部函数方法:state存储与返回状态。

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  // 也可以定义为
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++
    },
  },
})

在这里插入图片描述

修改state属性(五种方法)

1.直接修改值

Test.current=2

2.通过$patch修改,支持单个或多个属性修改

Test.$patch({current:33})

3.$patch工厂函数方式

  Test.$patch((state) => {
      state.current = 99;
      state.name = '范迪塞尔'
    })

4.$state 缺点是必须修改整个对象

   Test.$state = { current: 88, name: '123' }

5.action

Test.setCurrent()

Actions

Actions 相当于组件中的 methods。 它们可以使用 defineStore() 中的 actions 属性定义,并且它们非常适合定义业务逻辑:
store中使用actionsstore中使用actions

要是用的组件中调用
要是用的组件中调用

直接使用直接在要是用的组件中使用

Getters

Getter 完全等同于 Store 状态的 计算值。 它们可以用 defineStore() 中的 getters 属性定义
在这里插入图片描述
在这里插入图片描述

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  getters: {
    // 自动将返回类型推断为数字
    doubleCount(state) {
      return state.counter * 2
    },
    // 返回类型必须明确设置
    doublePlusOne(): number {
      return this.counter * 2 + 1
    },
  },
})

$reset()

通过调用 store 上的 $reset() 方法将状态 重置 到其初始值:

3.App中使用store

import { “store暴露的方法”} from 'store路径'

拿到store方法

const counter = useCounterStore()

修改时用counter点出内部状态。

counter.$patch({ count: counter.count + 1 })

图片示例:
在这里插入图片描述

四、使用场景

1.使用于setup

虽然 Composition API 并不适合所有人,但 setup() 钩子可以使在 Options API 中使用 Pinia 更容易。 不需要额外的 map helper!

import { useCounterStore } from '../stores/counterStore'

export default {
  setup() {
    const counterStore = useCounterStore()

    return { counterStore }
  },
  computed: {
    tripleCounter() {
      return counterStore.counter * 3
    },
  },
}

2.不使用setup()

如果您不使用 Composition API,并且使用的是 computed、methods、…,则可以使用 mapState() 帮助器将状态属性映射为只读计算属性:

import { mapState } from 'pinia'
import { useCounterStore } from '../stores/counterStore'

export default {
  computed: {
    // 允许访问组件内部的 this.counter
    // 与从 store.counter 读取相同
    ...mapState(useCounterStore, {
      myOwnName: 'counter',
      // 您还可以编写一个访问 store 的函数
      double: store => store.counter * 2,
      // 它可以正常读取“this”,但无法正常写入...
      magicValue(store) {
        return store.someGetter + this.counter + this.double
      },
    }),
  },
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐