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 }
})