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

相关推荐
海天胜景34 分钟前
vue3 el-table 行号
javascript·vue.js·ecmascript
小赖同学啊35 分钟前
深度解析 Element Plus
前端·javascript·vue.js
EndingCoder38 分钟前
从零基础到最佳实践:Vue.js 系列(3/10):《组件化开发入门》
前端·javascript·vue.js
职场马喽38 分钟前
vue+luckysheet导出功能(解决了样式为null的报错问题)
前端·javascript·vue.js
Mr.app40 分钟前
关于Vue自定义组件封装的属性/事件/插槽的透传问题
vue.js
北辰浮光41 分钟前
[Vue]路由基础使用和路径传参
前端·javascript·vue.js
難釋懷43 分钟前
Vue 简介
前端·javascript·vue.js
_龙小鱼_2 小时前
Vue Router动态路由与导航守卫实战
前端·javascript·vue.js·html5
源码云商2 小时前
基于Spring Boot + Vue的教师工作量管理系统设计与实现
vue.js·spring boot·后端
BillKu3 小时前
el-radio-group 与 el-dropdown 组合使用的注意事项
前端·javascript·vue.js