• Vue3学习——pinia


    官方:Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。

    安装

    npm i pinia
    
    • 1

    引入

    import { createPinia } from 'pinia'
    const pinia = createPinia()
    app.use(pinia)
    
    • 1
    • 2
    • 3

    此时浏览器的vuetool中就会有个菠萝🍍的图标

    使用

    store/count.ts

    import { defineStore } from 'pinia'
    export const useCountStore = defineStore('count', {
    	state(){
    		return {
    			token: 'xin',
    			name: 'kele'
    		}
    	},
    	action:{},
    	getter:{}
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    vue页面

    import { useCountStore  } from '@/store/count.ts'
    const countStore = useCountStore()
    // 获取state中的token
    console.log(countStore.token)
    
    • 1
    • 2
    • 3
    • 4

    修改数据

    在vuex中不可以直接改state的值,但pinia可以

    • 方式一
    // 直接vue文件改
    countStore.token = 'xxin'
    
    • 1
    • 2
    • 方式二
    // 批量修改
    countStore.$patch({
    	token: 'xx',
    	name: 'kelele'
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5

    观察工具pinia是批量变更是一次,所以批量变更推荐使用$patch

    • 方式三
    // actions写方法里
    export const useCountStore = defineStore('count', {
    	state(){
    		return {
    			token: 'xin',
    			name: 'kele'
    		}
    	},
    	action:{
    		changeToken() {
    			this.token = 'xinxin'
    		}
    	},
    	getter:{}
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    storeToRefs

    用于解构store里的数据(不会对方法进行包裹,只对数据ref)

    import { storeToRefs } from 'pinia'
    const { name } = storeToRefs(countStore)
    
    • 1
    • 2

    getter使用

    import { defineStore } from 'pinia'
    export const useCountStore = defineStore('count', {
    	state(){
    		return {
    			token: 'xin',
    			name: 'kele'
    		}
    	},
    	action:{},
    	getter:{
    		// 箭头函数不能用this
    		addToken: state => state.token + '~~',
    		// 不传参数state会飘红,不知道return的是什么类型;加个string类型就可以了
    		upperName():string{
    			return {
    				this.name.toUpperCase()
    			}
    		}
    	}
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    getter的数据也可解构拿到

    $subscribe

    相当于watch

    // 监听数据的变化
    store.$subscribe((args, state) => {
      console.log('args', args)
      console.log('state', state)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    C语言:动态内存分配(2)
    【spring】初识spring基础
    Java基础复习 Day 23
    基于安卓的校园信息助手系统设计(Eclipse开发)
    .NET序列化 serializable,反序列化
    GUI设计——PyQt5快速入门
    实验一、综合实验【Process on】
    微信小程序开发学习文档(万字总结,一篇搞定前端开发)
    怎么找通达信行情接口c++源码?
    软件无线电系列——模拟无线电、数字无线电、软件无线电
  • 原文地址:https://blog.csdn.net/m0_49494051/article/details/136340805