Pinia(小菠萝)使用方法

01 Pinia

相比较于Vuex,Pinia抛弃了Mutation操作,保留state,getters,actions,并且支持Typescript和Vue3的组合式Api。

02 安装

yarn add pinia
// 或者
npm install pinia

03 引入

  • 首先在项目根目录下创建store/index
// index.ts文件下
import { createPinia} from 'pinia'
// 实例化,也可以在main.ts文件中实例化,我习惯写在这是为了更好定位问题
const store = createPinia()

export default store
  • main.ts文件中挂载store实例
import { createApp } from 'vue'
import App from './App.vue'
// Pinia
import store from './store'

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

03 创建存储模块

  • 引入defineStore
import { createPinia, defineStore } from 'pinia'
const store = createPinia()

// 每一个存储的模块,命名规则use开头,store结尾
// defineStore提供两个参数,第一个参数为数据的id,第二参数接受一个对象(书写配置项)
export const useAuthStore = defineStore('auth', {
  state: () => {
    return {
      num: 0
    }
  },
  getters: {},
  actions: {},
})

export default store
  • Pinia一个亮点就是在存储模块中使用Vue3的setup语法,让代码扁平化
export const useAuthStore = defineStore('auth', () => {
  const num= ref(0)
  function increment() {
    num.value++
  }

  return { num, increment }
})
// ref() 就是 state 属性
// computed() 就是 getters
// function() 就是 actions

04 在组件中引用存储数据

  • 以下的方式只能调用store的数据,如果对数据进行更改,则无法实现响应式
<template>
  <div>
      <h2>{{ store.num }}</h2>
  </div>
</template>

<script setup lang="ts">
import { useAuthStore } from "../store/index";
const store = useAuthStore();
     
</script>
  • Pinia提供storeToRefs来做响应式数据
<template>
  <div>
      <h2>{{ store.num }}</h2>
  </div>
</template>

<script setup lang="ts">
import { useAuthStore } from "../store/index"
import { storeToRefs } from 'pinia'
const store = useAuthStore();
// 这样结构出来的数据是响应式的
const { num } = storeToRefs(store)

// 如果直接结构store实例,数据只能使用一次

</script>

05 $patch修改数据

在Vuex中,提供mutation来修改state数据。在Pinia数据模块中,可直接修改state数据,并且提供$patch来修改多条数据。虽然我们可以不用$patch就修改多条数据,但是Pinia提供的$patch让我们修改数据更加高效,相当于性能优化。

// $patch接收两个参数类型,对象和函数

<script setup lang="ts">
// $patch + 对象
  const store = useAuthStore()
  const change = () => {
    store.$patch({
      doubleCount: store.num * 2 
      moreCount: store.num++
    })
  }

// $patch + 函数
 const store = useAuthStore()
  const change = () => {
    store.$patch((state) => {
      state.num++
      state.count--
    })
  }
</script>

注意!$patch不接收异步函数

06 getters讲解

跟Vuex的getters概念相差不多,也是state的计算属性,并且可以通过this访问store实例

export const useStore = defineStore('main', {
  state: () => ({
    count: 0,
  }),
  getters: {
    //官方推荐使用箭头函数
    doubleCount:(state) => state.count *2,
    // getters之间相互引用
    doublePlusOne(): number {
      return this.doubleCount + 1
    },
    // 引用其他store的getters
    otherGetter(state) {
      const otherStore = useOtherStore()
      return state.localData + otherStore.data
    },
  },
})

07 actions讲解

跟getters一样,可以通过this访问store实例,可用于接收异步函数

import { mande } from 'mande'

const api = mande('/api/users')

export const useUsers = defineStore('users', {
  state: () => ({
    userData: null,
    // ...
  }),

  actions: {
    async registerUser(login, password) {
      try {
        this.userData = await api.post({ login, password })
        showTooltip(`Welcome back ${this.userData.name}!`)
      } catch (error) {
        showTooltip(error)
        // 让表单组件显示错误
        return error
      }
    },
  },
 // 也可以访问其他store的actions,具体操作参照上文getters
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值