Pinia的基本使用,Vuex的替代品

Pinia的基本使用,Vuex的替代品

以下操作均在vue3基础上进行

安装

npm install pinia

基本使用

1. 在main.js中引入pinia

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

const app = createApp(App)
const pinia = createPinia()
app.use(pinia)

app.mount('#app')

2. 在src下新建store目录,并创建index.js文件

  • 定义方式和vuex定义方式差不太多,只是用一个defineStore包起来了,然后state变成了匿名函数,移除了mutations;直接在actions中操作state的数据,更简洁,更方便。
  • 全程可以使用this操作state中定义的数据,注意不要使用箭头函数,会改变this的指向
import { defineStore } from 'pinia'

export const useMain = defineStore('main', {
  state: () => {
    return {
      count: 0
    }
  },
  getters: {
    getDoubleCount () {
      return this.count * 2
    }
  },
  actions: {
    increment () {
      this.count++
    },
    decrement () {
      this.count--
    }
  }
})

3. 在App.vue中使用刚刚定义的store

<template>
  <div>message: {{ store.message }}</div>
  <div>count: {{store.count}}</div>
  <div>double count: {{ store.getDoubleCount }}</div>
  <div><button @click="store.increment">increment count</button></div>
  <div><button @click="decrement">decrement count</button></div>
  <div><button @click="resetCount">reset count</button></div>
</template>

<script lang="ts" setup>
import { useMain } from './store/index'

const store = useMain()
const decrement = () => {
  store.decrement()
}
const resetCount = () => {
  // 可以调用快捷方式,重置state数据
  // store.$reset()
  store.$patch({
    count: 0,
    message: 'update message'
  })
}
</script>

更新state中的数据有几种方式

  1. 调用actions中定义的方法,更新state中的数据
  2. 官方建议更新数据使用$patch方法更新state数据,中间进行了优化
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潇洒哥GG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值