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 分钟前
从零用java实现 小红书 springboot vue uniapp(13)模仿抖音视频切换
java·vue.js·spring boot
加减法原则8 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js
天若有情6739 小时前
React、Vue、Angular的性能优化与源码解析概述
vue.js·react.js·angular.js
草巾冒小子10 小时前
vue3实战:.ts文件中的interface定义与抛出、其他文件的调用方式
前端·javascript·vue.js
eggcode10 小时前
Vue+Openlayers加载OSM、加载天地图
vue.js·openlayers·webgis
武昌库里写JAVA13 小时前
vue3面试题(个人笔记)
java·vue.js·spring boot·学习·课程设计
lalalalalalalala14 小时前
开箱即用的 Vue3 无限平滑滚动组件
前端·vue.js
前端Hardy14 小时前
8个你必须掌握的「Vue」实用技巧
前端·javascript·vue.js
久爱@勿忘15 小时前
第二章:创建登录页面
前端·vue.js·elementplus
Jinxiansen021115 小时前
Vue 3 中父子组件双向绑定的 4 种方式
javascript·vue.js·ecmascript