轻松搞定Vue3+Pinia-4-多个store

1. 前言

  1. Vue3大势不可阻挡,与之而来的就是Vite ,尤雨溪极力推荐的前端开发构建工具
  2. vue3原生支持TS ,所以TS语法和vue3TS语法学起来
  3. vue中的vuex状态管理也用不顺手,看不顺眼了,换为Pinia
  4. 文接上篇 Vue3+Pinia-3-getters
  5. 之前一套流程pinia共享state,访问,修改算是基础的使用了,接下里说下不太常用的东西

2. 新建一个store

  1. 新建 src/store/carStore.ts,模拟多个store的场景
  2. 操作都一样,直接上代码
import {defineStore} from 'pinia'
export const carStore = defineStore('carStoreId',{
    // 这种写法 有道友反馈看起来 还是需要反应下 
    // state:()=>({})
    state:()=>{
        return{
            carList:['唐-DMI','汉EV-千山翠','海豹','领跑C01']
        }
    }
})

3. 组件 使用 carStore

  1. 没有套路,就直接使用
  2. src/components/HelloCar.vue
  3. 在App.vue中引入组件显示 看效果





  1. 效果图
    1.png
  2. 组合式API,像组装积木一样,功能分割,需要啥组到一起就行
  3. 调试多个store
    调试.png

4. store互相调用

4.1 场景分析

  1. 一个store想使用另外一个store内的数据咋办呢
  2. 拿上述的这个 carStorehelloStore为例
  3. 需求:helloStore使用 carStore里面的数据carList

4.2 helloStore配置

  1. 整体思路是 在actions中定义函数,函数中访问其他store数据
  2. 引入 import {carStore} from './carStore'
  3. actions 配置 函数/getCarList
  4. 函数内部用carStore()访问carStore自己的数据
import {carStore} from './carStore'
export const helloStore = defineStore("hello", {
    // 必须用箭头函数
    state: () => ({
        name:'温言铁语',
        age: 71,
        phone:"18603038753",//手机号中间四位 *代替 脱敏处理
    }),
    actions:{
        updateState(){
            this.age ++
            this.name = 'yzs'
        },
        getCarList(){
            console.log("-------carStore",carStore().carList);
        }
    },
    getters:{
        starPhone(state){
            console.log("缓存---值一样不会被多次调用");
            return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/ ,'$1****$2')
        }
    }
});

5. 组件内使用

  1. 添加一个获取按钮
        
  1. 事件实现逻辑
const store = helloStore()
const getList = ()=>{
    store.getCarList()
 //  可以赋值给当前界面的数据
}
  1. 查看控制台打印,证明调用并获取到了 carStore的数据

6. 后记

  1. 推荐下载插件的地址
  2. Volar比vetur更强大的 vscode插件,提供了更好的vue3语法支持
  3. 全名Vue Language Features (Volar) 骷髅头/☠️,向着 one piece出发吧

参考资料

Vite
Pinia
轻松搞定 Vue3+Vite+Pinia-1-state
轻松搞定 Vue3+Vite+Pinia-2-state-修改
轻松搞定 Vue3+Vite+Pinia-3-getters


初心

我所有的文章都只是基于入门,初步的了解;是自己的知识体系梳理,如有错误,道友们一起沟通交流;
如果能帮助到有缘人,非常的荣幸,一切为了部落的崛起;
共勉

你可能感兴趣的:(轻松搞定Vue3+Pinia-4-多个store)