在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>
相关推荐
九九落4 小时前
前端获取经纬度完全指南:从Geolocation API到地图集成
前端·获取经纬度
来恩10035 小时前
jQuery选择器
前端·javascript·jquery
前端繁华如梦5 小时前
树上挂苹果还是挂玻璃球?Three.js 程序化果实的完整实现指南
前端·javascript
墨痕诉清风5 小时前
Web浏览器客户端检测网站网络健康(代码)
前端·网络·测试工具
IMPYLH5 小时前
Linux 的 wc 命令
linux·运维·服务器·前端·bash
happybasic5 小时前
Python库升级标准流程~
linux·前端·python
川冰ICE5 小时前
前端工程化深度实战:从Webpack5到Vite5的构建工具演进与选型决策
前端
CDwenhuohuo5 小时前
优惠券组件直接用 uview plus
前端·javascript·vue.js
用户74090472362755 小时前
我用 curl 排查了一次 OpenAI-compatible API 连接失败:401、403、404 分别怎么定位
前端
kft13145 小时前
XSS深度剖析:从弹窗到持久化窃取Cookie
前端·web安全·xss·安全测试