值得庆幸的是Pinia不需要像Vuex一样使用modules分模块,只需要在store目录中直接定义对应模块就可以了,因此,你可以先简单理解为它是根据文件目录划分的。文章后面还会讲到分模块后,模块之前的数据该怎么通信
1 2 3 | store/user.js store/shop.js ... |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import { defineStore } from 'pinia' export const user = defineStore({ id: 'user', state:()=>{ return { userInfo:{ nickName:'章三' }, token:'xfdfdsjkdsj' } }, getters:{ }, actions:{ } }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 | <template> <div> <h1>A组件</h1> {{ userInfo.nickName }} </div> </template> <script setup> import { storeToRefs } from 'pinia' import { user } from '../store/user' const store = user(); let { userInfo } = storeToRefs(store); </script> |
需求:在pinia a文件的action中定义一个方法,想修改pinia b里面的data,之前vuex有rootState,{ root: true }参数那些,那么在pinia中该如何修改?实际上我们只需要在pinia a文件导入pinia b,然后就可以获取到pinia b的store实力,注意,Pinia的每个模块文件的id一定得是唯一的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <template> <div> <h2>store测试</h2> <p>{{ textData }}</p> <el-button type="primary" @click="reduceCunt">减少</el-button> <el-button type="primary" @click="addCunt">增加</el-button> <h2>子组件pinia_B</h2> <pinia_b></pinia_b> <br> <el-button id="noModel" type="primary" @click="changeAtoB">组件A通过Pinia修改子组件B</el-button> </div> </template> <script setup lang="ts"> import pinia_b from './pinia_b.vue' import { useStoreA } from '@/store/modules/page_a' const storeA = useStoreA(); let changeAtoB = () => { console.log('storeA', storeA); storeA.calcUpdata() } </script> <style scoped> </style> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <template> <div> <h3>pinia子组件pniaBcuntData值------{{ pniaBcuntData }}</h3> </div> </template> <script setup lang="ts"> import { useStoreB } from '@/store/modules/page_b' const piniaBstore = useStoreB(); let { pniaBcuntData } = storeToRefs(piniaBstore); </script> <style scoped> </style> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import { defineStore } from 'pinia'; import { useStoreB } from '@/store/modules/page_b'; const storeB = useStoreB(); let { pniaBcuntData } = storeToRefs(storeB); export const useStoreA = defineStore('storeIdA', { state: () => { return { count: 100, }; }, getters: {}, actions: { myTest(){ console.log(1) }, calcUpdata() { pniaBcuntData.value = '改变了'; }, }, }); |
1 2 3 4 5 6 7 8 9 10 11 | import { defineStore } from 'pinia' export const useStoreB = defineStore('storeIdB', { state: () => { return { pniaBcuntData: '默认值', } }, getters:{}, actions:{} }) |
上一篇:Vue3中Pinia实现数据状态管理state、getters、actions
下一篇:Pinia如何让数据持久化存储?
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"Pinia如何modules模块划分、模块之间如何通信?"
最新评论