关于vue3 菠萝 Pinia 使用

关于vue3 菠萝 Pinia 使用

  • 官网案例
import { defineStore } from 'pinia'

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useAlertsStore = defineStore('alerts', {
  // 其他配置...
})
  • 对于官网案例的解释
	defineStore:用来定义类似于一个 新的.vue文件 也可以理解为命名空间 nameScoped:true  模块名 两个参数
	 defineStore('alerts', {})
	 alerts: 可以理解为模块名
 	{}:中间包含 state可以理解为 一个data(){return {
	   中间是我们定义的数据
		a:'你是一个大麻瓜'
	}}
	
	 state: () => ({ count: 0 }),
	面试题:有人会问为什么Pinia中的state是一个箭头函数
				个人理解:倘若你用的是vue3+ts 他可以更好的推断 数据中的ts类型
				还有一点就是 我们会用到 actions 那么 actions 中间要改变 state 中的状态 需要用到this 
				箭头函数的this指向 alerts 模块 你要是用了 function 那么 state 属于一个闭包 
				个人理解哈 有错误评论区可以评论出来 	
  • actions 不能说与 vuex 中的 actions 一致 但是 也差不多 同样支持 一步请求 只不过不需要再去调用mountions 方法 单词可能打错了 见怪莫怪
	// 先看 官网 给的 例子 
		 actions: {
   			 increment() {  // 定义的 方法  this指向当前 父级作用域 也就是 state 返回出来的 counter
      			this.counter++ // 可以直接更改 state 中的数据
   			 },
   		 randomizeCounter() {
    		  this.counter = Math.round(100 * Math.random())
        },
		async getBannerList:{
					...(res)=>{
				this.bannerList = res.data
			}
		}
  },
  • getters 计算属性
 getters: {
 	//对外丢出 轮播图 列表
    exportBannerList(){
    		// 可在此处理 state中的 数据 如 foreach map 等等逻辑
			return this.bannerList
	}
  },
  • 使用 useAlertsStore 模块
// setup 中 使用 
import  useAlertsStore form '文件路径'
const store = useAlertsStore()

// 调用bannerList 数据 
const list = compound(()=>{
return store.exportBannerList()
})

//调用 actions 中的方法
store.increment()

// 更新 state 中的 数据 
store.$pach({ // 可以同时更新 多个
	key:value
})


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值