pinia 使用状态管理
一、定义状态变量、方法
在 src\stores\ 目录下,新建状态管理文件 counter.ts
为了确保改变状态的逻辑像状态本身一样集中,建议在 store 上定义方法,方法的名称应该要能表达出行动的意图:
import { ref, computed } from 'vue' import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', () => { const count = ref(0) const doubleCount = computed(() => count.value * 2) function increment() { count.value++ } return { count, doubleCount, increment } })
二、在组件中使用状态存储变更、方法
<script setup lang="ts"> import { useCounterStore } from '../stores/counter' const counterStore = useCounterStore() </script> <template> <div> <el-button type="success" @click="counterStore.increment">Success</el-button> <h1>{{ counterStore.count }}</h1> </div> </template> <style lang="scss" scoped></style>