Getter

getter 介绍

Getter 等同于 store 的 state 的计算值。可以通过 defineStore() 中的 getters 属性来定义它们。推荐使用箭头函数,并且它将接收 state 作为第一个参数,定义演示 :

import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter',{
  state : ()=>{
    return {
      count : 0
    }
  },
  getters : {
    doubleCount : (state)=>{
      return state.count +  2;
    }
  }
})

调用演示

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