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 小时前
超级好用的三原后台管理v1.0.0发布🎉(Vue3 + Ant Design Vue + Java Spring Boot )附源码
java·vue.js·开源
之歆9 小时前
RBAC权限模型设计与实现深度解析
vue.js
前端Hardy9 小时前
Vue 项目必备:10 个高频实用自定义指令,直接复制即用(Vue2 / Vue3 通用)
前端·javascript·vue.js
懒大王95279 小时前
Vue 2 与 Vue 3 的区别
前端·javascript·vue.js
xuankuxiaoyao9 小时前
vue.js 实践--侦听器和样式绑定
前端·javascript·vue.js
小沐°10 小时前
vue3+element-plus 实现动态菜单和动态路由的渲染
前端·javascript·vue.js
ct97810 小时前
Vue3 状态管理方案:Pinia 全指南
javascript·vue.js
Java小卷10 小时前
前端表单构建神器 - formkit初体验
vue.js·低代码
计算机学姐11 小时前
基于SpringBoot的在线学习网站平台【个性化推荐+数据可视化+课程章节学习】
java·vue.js·spring boot·后端·学习·mysql·信息可视化
暴力袋鼠哥11 小时前
基于 Django 与 Vue 的汽车数据分析系统设计与实现
vue.js·django·汽车