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

相关推荐
她是太阳,好耀眼i1 小时前
Nvm 实现vue版本切换
javascript·vue.js·ecmascript
键盘飞行员1 小时前
Vue3+TypeScript项目中配置自动导入功能,遇到了问题需要详细的配置教程!
前端·typescript·vue
han_1 小时前
前端高频面试题之Vue(初、中级篇)
前端·vue.js·面试
执携2 小时前
Vue Router (命名视图)
前端·javascript·vue.js
含若飞3 小时前
Vue 中 `watch` 与 `this.$watch` 使用指南
前端·javascript·vue.js
希冀1234 小时前
【Vue】第五篇
前端·javascript·vue.js
华仔啊5 小时前
开源一款 SpringBoot3 + Vue3 数据库文档工具,自动生成 Markdown/HTML
vue.js·spring boot·后端
来碗盐焗星球5 小时前
简单聊下enum(枚举)
typescript
Patrick_Wilson5 小时前
AI会如何评价一名前端工程师的技术人格
前端·typescript·ai编程
一枚前端小能手5 小时前
「周更第11期」实用JS库推荐:Pinia
前端·javascript·vue.js