Skip to content

案例代码

ts

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 1️⃣ userInfo(对象,你来编)
  const userInfo = ref({
    id: 1,
    name: '张三',
    email: 'zhangsan@example.com',
    age: 25,
    isActive: true
  })

  // 2️⃣ MyProduct(一个数据,这里假设是字符串)
  const MyProduct = ref('苹果手机')

  // 3️⃣ MyText(文本)
  const MyText = ref('这是一段示例文本')

  // 4️⃣ MyInt(整数)
  const MyInt = ref(42)

  // 5️⃣ MyDouble(小数)
  const MyDouble = ref(3.14159)

  // 6️⃣ Mytime(时间,用 Date 对象或字符串)
  const Mytime = ref(new Date().toISOString()) // 或 new Date()

  // 7️⃣ MyAll(计算属性,返回之前的总和,比如 MyInt + MyDouble)
  const MyAll = computed(() => {
    return MyInt.value + MyDouble.value
  })

  // 方法(action)用来更新数据
  function updateUserInfo(newInfo: Partial<typeof userInfo.value>) {
    userInfo.value = { ...userInfo.value, ...newInfo }
  }

  function setProduct(product: string) {
    MyProduct.value = product
  }

  function setText(text: string) {
    MyText.value = text
  }

  function setInt(val: number) {
    MyInt.value = val
  }

  function setDouble(val: number) {
    MyDouble.value = val
  }

  function updateTime() {
    Mytime.value = new Date().toISOString()
  }

  // 也可以定义一个重置所有的方法
  function resetAll() {
    MyInt.value = 0
    MyDouble.value = 0
    MyText.value = ''
    MyProduct.value = ''
    Mytime.value = new Date().toISOString()
    userInfo.value = { id: 0, name: '', email: '', age: 0, isActive: false }
  }

  // 暴露所有状态和方法
  return {
    userInfo,
    MyProduct,
    MyText,
    MyInt,
    MyDouble,
    Mytime,
    MyAll, // 计算属性
    updateUserInfo,
    setProduct,
    setText,
    setInt,
    setDouble,
    updateTime,
    resetAll
  }
})
vue
<template>
  <div>
    <p>{{ store.MyText }}</p>
    <input v-model="store.MyText" />
    <p>{{ store.MyInt }}</p>
    <button @click="store.MyInt++">+1</button>
  </div>
</template>

<script setup>
import { useUserStore } from '@/stores/userStore'
const store = useUserStore()
</script>