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 分钟前
Vue+ts 如何实现父组件和子组件通信
javascript·vue.js·ecmascript
fury_12341 分钟前
vue3:数组的.includes方法怎么使用
前端·javascript·vue.js
weixin_4050233743 分钟前
包资源管理器NPM 使用
前端·npm·node.js
宁&沉沦1 小时前
Cursor 科技感的登录页面提示词
前端·javascript·vue.js
武天1 小时前
如果使用Vue3.0实现一个 Modal,你会怎么进行设计?
vue.js
熊猫钓鱼>_>3 小时前
TypeScript前端架构与开发技巧深度解析:从工程化到性能优化的完整实践
前端·javascript·typescript
敲敲敲敲暴你脑袋3 小时前
Canvas绘制自定义流动路径
vue.js·typescript·canvas
盛夏绽放3 小时前
uni-app Vue 项目的规范目录结构全解
前端·vue.js·uni-app
国家不保护废物4 小时前
Vue组件通信全攻略:从父子传到事件总线,玩转组件数据流!
前端·vue.js
写不来代码的草莓熊4 小时前
vue前端面试题——记录一次面试当中遇到的题(9)
前端·javascript·vue.js