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

相关推荐
老毛肚9 小时前
jeecgboot vue TS & 模板化 04
前端·javascript·vue.js
卤蛋fg614 小时前
高性能 Vue 甘特图:vxe-gantt 如何秒级渲染万级任务数据
vue.js
逐光老顽童16 小时前
用 Go 实现一个 LLM 路由网关:Thompson Sampling 与自适应故障转移实践
vue.js·go
小小龙学IT18 小时前
Drizzle ORM:TypeScript 生态中冉冉升起的数据库工具链引言
javascript·数据库·typescript
xkxnq21 小时前
第八阶段:工程化、质量管控与高级拓展(132天),Vue项目文档自动化:VuePress搭建组件文档(组件示例+API说明)
javascript·vue.js·自动化
lantian1 天前
TypeScript 模块系统核心原理:从ESM到CJS,彻底搞懂模块格式与解析逻辑
前端·typescript·ecmascript 6
且听风吟_xincell1 天前
从零用 TypeScript 写一个 TCP 聊天室(下)——数据持久化、登录验证与管理指令
jvm·tcp/ip·typescript
ct9781 天前
Promise
前端·javascript·vue.js
不瘦80斤不改名1 天前
TypeScript核心知识全解析
typescript
很楠爱上1 天前
TypeScript 核心知识精要
javascript·ubuntu·typescript