vue3 pinia 中actions修改状态不生效

复制代码
import { defineStore } from "pinia";
import { useother } from "./otherstore";
export const useStore = defineStore("main", {
  state: () => {
    return {
      count: 3,
      name: "zhangs",
      isadmin: true,
    };
  },
  getters: {
    addcount(state) {
      // return state.count+3
      const oth = useother();

      return this.count + oth.count;
    },
  },
  actions: {
    getaddcount(state) {
        console.log(state)
      this.count++
    },
 getnumcount(num) {
        this.count+=num
    }
  },
});

如上述代码,在actions中定义getaddcount方法 对count做了操作

复制代码
<template>
    <div>
piniatest page --<br/>
count---{{ count }}---{{ addcount }}<br/>
<button @click="handleadd">添加count</button>
<button @click="handleaddnum(3)">添加num的count</button>

    </div>
</template>

<script setup>
import {useStore} from '@/store'
import { storeToRefs } from 'pinia';
const store = useStore();
const {count,name,isadmin,addcount} = storeToRefs(store)
// const count = store.count
// const addcount = store.addcount
const handleadd = () => {
    // console.log(99)
    store.getaddcount()
}
const handleaddnum = (num)=> {
    store.getnumcount(num)
}
</script>

<style lang="scss" scoped>

</style>

在组件中使用时,如果直接操作store.getaddcount()则页面上数据变动不生效

解决:引入pinia中的storeToRefs

使store中的变量变为响应式的即可;

相关推荐
mCell5 小时前
DeepSeek Harness 速览:“一切皆插件”意味着什么
typescript·agent·deepseek
京东云开发者12 小时前
【全栈实践】第一个 AI Agent 项目:从零搭建 AI 音频创作助手(入门篇)
typescript·agent·vuex
夏幻灵12 小时前
Vue 2 与 Vue 3 在应用初始化上的设计差异与技术演进
前端·javascript·vue.js
王林不想说话16 小时前
React + Ant Design 后台项目:63 个业务组件的分层实践
react.js·typescript·ant design
Sterting17 小时前
Form表单与校验
javascript·vue.js·elementui
大家的林语冰17 小时前
👍 超越 ESLint,Oxc 优先采用 TypeScript 7,Rust 和 Go 梦幻联动!
前端·javascript·typescript
embedded大铭19 小时前
ai时代上站记录
typescript
cyadyx20 小时前
【vue】Pinia相对Vuex
前端·javascript·vue.js
紫禁玄科1 天前
Shai-Hulud:npm生态的自我复制蠕虫风暴
前端·npm·node.js
用户938515635071 天前
从零在浏览器里跑 DeepSeek-R1:WebGPU + Transformers.js 全链路实战(三)
前端·react.js·typescript