直接修改
<template> <div>{{ store.count }}</div> <button @click="add">+1</button> </template> <script setup> import { useStore } from '@/store/index'; let store = useStore() const add = () => { store.count++ } </script>
调用$patch
<template> <div>{{ store.count }}</div> <button @click="add">+1</button> </template> <script setup> import { useStore } from '@/store/index'; let store = useStore() const add = () => { store.$patch({ count: store.count + 1, msg: 'hello pinia!' }) } </script>
$patch加函数的形式修改状态数据
import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => { return { msg: 'hello world!', count: 0, userInfo: { name:'张三' }, userItems: [] } }, getters: {}, actions: {} })