pinia的使用

前言:

当我们构建一个中大型单页应用,需要考虑如何更好地在组件外部管理状态的时候,我们就会借助一些状态管理器帮助我们完成这些操作。

相比于 VuexPinia 提供了更简洁直接的组合式风格的API(去掉了 mutation ),action可以支持同步和异步。去掉了 modules 的概念,每一个 store 都是一个独立的模块。

其次,在使用 TypeScript 时也提供了比较完善的类型推导。所以在开发vue3的项目的时候,我们更为推荐使用pinia。

安装pinia

pnpm install pinia
# or with yarn
yarn add pinia
# or with npm
npm install pinia

创建pinia 实例

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

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

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

定义store示例

import { defineStore } from 'pinia'

//您可以将'defineStore()'的返回值命名为任意名称,

//但最好使用store的名称,并用“use”将其包围,这是一个不错的规范

//(例如`useUserStore`、`useCartStore`和`useProductStore`)

//第一个参数是应用程序中存储的唯一id
export const useAdminStore = defineStore('admin', {
  // 其他选项...
})

//定义一个完整的store
//与 Vue的选项API类似,我们也可以传递带有属性的选项对象。state actions getters
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0, name: 'Eduardo' }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})
//您可以将其视为store的属性,也可以将其视为vue的属性,
//state => data
//getters => computed
//actions => methods
//这样会更容易记忆

/* 还有另一种可能的语法来定义存储。与 Vue3组合API的设置函数类似,
我们可以传入一个函数来定义反应式属性和方法,并返回一个包含我们要公
开的属性和方法的对象。*/
export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const name = ref('Eduardo')
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, name, doubleCount, increment }
})

使用pinia

<script setup>
import { useAdminStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
    
const store = useAdminStore()
//结构并赋予响应性
const { name } = storeToRefs(store)
console.log('name',name)
</script>

剖析pinia各个选项

state

//给 state 加上类型推导
interface UserInfo {
  name: string
  age: number
}

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      userList: [] as UserInfo[],
      user: null as UserInfo | null,
    }
  },
})


//或者给整个state加上类型推导
interface UserInfo {
  name: string
  age: number
}

interface State {
  userList: UserInfo[]
  user: UserInfo | null
}

export const useUserStore = defineStore('user', {
  state: (): State => {
    return {
      userList: [],
      user: null,
    }
  },
})
访问state
import { useAdminStore } from '@/stores/user'
    
const store = useAdminStore()
console.log('name',store.name)
重置state
import { useAdminStore } from '@/stores/user'
    
const store = useAdminStore()
store..$reset()
更改state
//1.直接改变
store.name = 'new name'
//2.$patch
store.$patch({
  sex: 1,
  age: store.age + 1,
  name: 'new name',
})
//或
useUserStore.$patch((state) => {
  state.items.push({ name: 'jack', age: 18 })
  state.ishasStatus = true
})

getters

定义getters
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
})
//添加类型约束
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    // automatically infers the return type as a number
    doubleCount(state) {
      return state.count * 2
    },
    // the return type **must** be explicitly set
    doublePlusOne(): number {
      // autocompletion and typings for the whole store ✨
      return this.doubleCount + 1
    },
  },
})
访问getters
<template>
  <p>Double count is {{ store.doubleCount }}</p>
</template>

<script setup>
const store = useCounterStore()
</script>
访问其他getters
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    doubleCountPlusOne() {
      // autocompletion
      return this.doubleCount + 1
    },
  },
})
getters参数传递
//@/stores/admin
export const useAdminStore = defineStore('admin', {
  getters: {
    getUserById: (state) => {
      return (userId) => state.users.find((user) => user.id === userId)
    },
  },
})

//组件中使用
<template>
  <p>User 2: {{ getUserById(2) }}</p>
</template>

<script setup>
 import { useAdminStore } from '@/stores/admin' 
 const store = useAdminStore()
 const getUserById = store.getUserById
</script>

actions

定义actions
export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  actions: {
    // 因为我们依赖“this”,所以不能使用箭头函数
    increment() {
      this.count++
    },
    randomizeCounter() {
      this.count = Math.round(100 * Math.random())
    },
  },
})
/*与 getter 一样,操作通过完全键入(和自动完成)支持来访问整个商店实例。
与 getter 不同,操作可以是异步的*/
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 })
        console.log(`Welcome back ${this.userData.name}!`)
      } catch (error) {
        console.log(error)
        // let the form component display the error
        return error
      }
    },
  },
})
使用actions
<script setuo>
import { useCounterStore } from '@/store/counter'
const store = useCounterStore()
store.randomizeCounter()
</script>
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

零凌林

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

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

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

打赏作者

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

抵扣说明:

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

余额充值