在Vue3和TypeScripts中使用pinia

定义(state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods))

TypeScript 复制代码
// 引入pinia 和 vue
import { defineStore } from 'pinia'
import { ref, computed } from 'vue';
// 定义了一个名为 counter 的 store
export const useStore = defineStore('counter', ()=> {
    // 定义
    const count = ref(0)
    const userName = ref('')

    // Getter(计算属性)------ 只读
    const upperName = computed(() => userName.value.toUpperCase())
    // Action ------ 修改状态的方法
    function increment() {
        count.value++
    }

    function setUserName(name) {
        userName.value = name
    }
    
    
    // 重置函数
    function $reset() {
        count.value = 0
    }
    // 必须 return 所有要暴露的内容
    return {
        count,
        userName,
        increment,
        setUserName,
        $reset
    }
}

在组件中调用

TypeScript 复制代码
<template>
  <p>Count: {{ store.count }}</p>
  <p>Upper Name: {{ store.upperName }}</p>
  <button @click="store.increment">+1</button>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'

const store = useCounterStore()

// 调用 action
store.increment()
store.setUserName('Alice')

// 读取 state 或 getter(像属性一样访问)
console.log(store.count)       // 1
console.log(store.upperName)   // "ALICE"
</script>
相关推荐
IT_陈寒7 小时前
Redis那个过期删除策略,差点让我线上崩了
前端·人工智能·后端
jianqiang.xue7 小时前
Espressif-IDE进入维护模式:乐鑫把ESP32开发的宝押给VS Code
前端·css·ide
特创数字科技8 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
心之语歌8 小时前
uni-app uts原生插件开发:uts 与 Kotlin 交互踩坑实录(附解决方案)
前端·后端
再吃一根胡萝卜8 小时前
DSH 插件数据链路:Host 管数据,Client 只管画
前端
feixing_fx8 小时前
CSS 变量(Custom Properties):构建可扩展的主题切换系统
前端·css·前端框架·html·css3
十有八七10 小时前
手搓 Agent(一):先有大脑——大模型只会做一件事
前端·人工智能·后端
锋行天下10 小时前
「踩坑实录」给 LangGraph Agent 接两个 FastMCP,我被 langchain 偷偷改了工具名
前端·人工智能·后端
跳跳的小星星10 小时前
自研组件】Vue2 + ElementUI 通用列表页封装 wkjp-list-page,一套配置搞定搜索、动态表格、分页、增删改
前端
tryCbest10 小时前
Vue3—— 第 18 篇:Vue 2 到 Vue 3 迁移指南——升级避坑全记录
前端·vue.js