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