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中的变量变为响应式的即可;

相关推荐
非优秀程序员7 小时前
第04章 邮箱大战,163 与 QQ 的暗战|《互联网产品恩仇录》
java·vue.js·架构
周杰伦的稻香7 小时前
Hexo 腾讯视频追剧页插件:hexo-tengxun-eucalyptus 安装使用
npm
tryCbest13 小时前
Vue系列——第 15 篇:内置组件全家桶——Transition、Teleport、Suspense、KeepAlive
前端·vue.js
浪遏16 小时前
07|网页上看着正常,导出的 PDF 为什么还会变样
typescript
浪遏16 小时前
03|自动保存真正难的部分,是保存期间又发生了修改
typescript
浪遏16 小时前
04|同一篇资料,怎样同时交给编辑器、搜索和 AI
typescript
浪遏16 小时前
09|让 Mermaid 和 HTML 成为可编辑内容块
typescript
徐小夕18 小时前
开源Vector-Graph-RAG:向量+图谱双引擎,打破纯向量RAG的效果天花板
前端·vue.js·github
️公子20 小时前
可插拔 13 款实时棋牌对战平台实践:房间容器、Plugin SDK 与幂等账本
websocket·typescript·游戏开发·monorepo·插件架构·棋牌平台·实时对战
FungLeo21 小时前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome