【pinia】Store的两种声明方式:Option和Setup声明

1. Option选项式声明

state: 存放共享数据
getters: 相当于计算属性
actions:异步操作

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),//为了完整类型推理,推荐使用箭头函数
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

使用时:

<template>
  {{ store.count }}
</<template>
<script setup>
import { useCounterStore } from './store'
const store = useCounterStore()
</script>

注意:如果需要让state中的值变成响应式,需要用storeToRefs()

<template>
  <button @click="changeCount"></button>
  {{ count }}
</<template>
<script setup>
import { useCounterStore } from './store'
import { storeToRefs } from 'pinia'

const store = useCounterStore()
const { count } = storeToRefs(store)// count会变成响应式的 ref

const changeCount = () => {
	store.increment()
}
</script>

2. Setup组合式声明

ref() 就是 state 属性
computed() 就是 getters
function() 就是 actions (也可以写成箭头函数方式)

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const increment = () => {
    count.value++
  }
  
  return { count, increment }
})

使用时和Option选项式声明一样。
要让store数据变成响应性,也要使用 storeToRefs()

注意:如果使用reactive声明数据,修改状态时会不生效!!

3. 两种声明的区别点

使用选项式声明 时,可以通过调用 store 的 $reset() 方法将 state 重置为初始值。
但在Setup声明时,需要手动创建自己的$reset()方法,去重置数据。

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const increment = () => {
    count.value++
  }
  const $reset = () => {
  	count.value = 0
  }
  return { count, increment,$reset }
})
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值