State

state

state 用于存储状态数据,是 store 的核心。通常开发者会先定义能 state。在 Pinia 中,state 被定义为一个返回初始状态的函数。

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter',{
  state : ()=>{
    return {
      count : 0
    }
  }
})

setup 语法

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
    const count = ref(0)

    return { count, name }
})

访问 state

默认情况下,可以通过 store 实例访问 state,直接对其进行读写。

<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '/src/store/store'
const store = useCounterStore()
const { count } = storeToRefs(store)
const { increment } = store
const add = function(){
  console.log(count.value);
  store.count++;
  //count.value++;
}
</script>
<template>
  <div>
    <div>数值 : {{ count }}</div>
    <div>
      <button @click="add">+ 1</button>
    </div>
  </div>
</template>
<style scoped>
</style>

重置 state

你可以通过调用 store 的 $reset() 方法将 state 重置为初始值。

<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '/src/store/store'
const store = useCounterStore()
const { count } = storeToRefs(store)
const { increment } = store
const add = function(){
  console.log(count.value);
  store.count++;
  //count.value++;
}
const reset = function(){
  store.$reset();
}
</script>
<template>
  <div>
    <div>数值 : {{ count }}</div>
    <div>
      <button @click="add">+ 1</button>
      <button @click="reset">reset</button>
    </div>
  </div>
</template>
<style scoped>
</style>