vuex5 Pinia状态管理

1、配置
	import { createPinia } from 'pinia'

	app.use(createPinia())

2、基本使用
	(1)创建store
		.导出命名通过use开头
		
		import { defineStore,createPinia } from 'pinia'
		
		方式一:通过之前vuex的配置项格式以及mapState等辅助函数的使用
			const useCounterStore = defineStore('counter', {
			  state: () => ({ count: 0 }),
			  getters: {
			    double: (state) => state.count * 2,
			  },
			  actions: {
			    increment() {
			      this.count++
			    }
			  }
			})
			
			组件中:
				export default {
				  computed: {
				    ...mapStores(useCounterStore, useUserStore)
				    ...mapState(useCounterStore, ['count', 'double']),
				  },
				  methods: {
				    ...mapActions(useCounterStore, ['increment']),
				  },
				}
	
		方式二:通过函数形式
			export const useCounterStore = defineStore('counter', () => {
			  const count = ref(0)
			  function increment() {
			    count.value++
			  }
			
			  return { count, increment }
			})
	
	(2)store使用
		.导入定义的store
		.不要对导入的store的state进行解构赋值,否则会丢失其响应性
		.actions可以直接进行解构
		
		import { storeToRefs } from 'pinia'
		
		export default defineComponent({
		  setup() {
		    const store = useStore()
			
			不能使用解构赋值state,否则会丢失响应性
		    const { name, doubleCount } = store
			
			通过storeToRefs进行解构,不会丢失响应性
			const { name, doubleCount } = storeToRefs(store)
			
			可以直接进行解构actions
			const { increment } = store
					
		    return {
		      doubleValue: computed(() => store.doubleCount),
		    }
		  },
		})
	
	(3)state使用
		(1)改变state
			方式一:
				store.counter++
			
			方式二:
				选项式通过:mapState、mapWritableState辅助函数
			
			方式三:通过$patch
				(1)通过patch一个对象
					.对于数组的push操作等,需要重新返回一个新对象
					
					store.$patch({
					  counter: store.counter + 1,
					  name: 'Abalam',
					})
					
				(2)通过patch一个方法
					.对于这种方式数组的push操作等直接在原对象操作即可
					
					store.$patch((state) => {
					  state.items.push({ name: 'shoes', quantity: 1 })
					  state.hasChanged = true
					})
				
		
		(2)恢复、替换state
			恢复state为初始化状态
				store.$reset()					
				
			替换整个state
				store.$state = { counter: 666, name: 'Paimon' }	
				
				SSR使用
				const pinia = createPinia()
				pinia.state.value = {}; 			
				
		(3)监听state修改
			
			方式一:
				.相比watch监听更能够追溯状态
				
				store.$subscribe((mutation, state) => {
					mutation:
					  修改方式
					  	mutation.type 	'direct' | 'patch object' | 'patch function'
					  
					  修改的store名称
					  	mutation.storeId
					  
					  patch的对象,只有当patch一个对象时才会有
					 	mutation.payload

				},{
					detached: true	监听器不会在组件卸载时移除,默认会
				})
		
			方式二:
				watch(
				  pinia.state,
				  (state) => {
				  	...
				  },
				  { deep: true }
				)
		
	
	(4)getters使用
		1、定义
		
		import { useOtherStore } from './other-store'
		
		export const useStore = defineStore('main', {
		  state: () => ({
		    counter: 0,
		  }),
		  getters: {
			(1)第一个参数为state
			    doubleCount(state) {
			      return state.counter * 2
			    },
		    
			(2)使用其他getters
			    doublePlusOne(): number {
			      return this.doubleCount + 1
			    },
			    
		    (3)创建接受参数的getter
		    	getActiveUserById(state) {
			      const activeUsers = state.users.filter((user) => user.active)
			      return (userId) => activeUsers.find((user) => user.id === userId)
			    },
		    	
		    (4)使用其他store中的getters
		    	otherGetter(state) {
			      const otherStore = useOtherStore()
			      return state.localData + otherStore.data
			    },
		  },
		})
		
		2、使用getters
			(1)通过store直接使用
				const store = useStore()
			
			(2)通过mapState辅助函数
				export default {
				  computed: {
				    ...mapState(useCounterStore, ['doubleCount'])
				    ...mapState(useCounterStore, {
				      myOwnName: 'doubleCounter',
				      // you can also write a function that gets access to the store
				      double: store => store.doubleCount,
				    }),
				  },
				}
	
	
	(5)actions使用
		直接通过this来设置state,无需再通过同步方法
		1、定义
		export const useStore = defineStore('main', {
		  state: () => ({
		    counter: 0,
		  }),
		  actions: {
		    increment() {
		      this.counter++  通过this访问store中的其他内容
		    },
		    async randomizeCounter() {
		      this.counter = await fn();
		    },
		  },
		})
		
		2、使用
			.actions可直接解构使用
			
			(1)通过store直接使用
			(2)通过mapActions
				export default {
				  methods: {
				    ...mapActions(useCounterStore, ['increment'])
				    // same as above but registers it as this.myOwnName()
				    ...mapActions(useCounterStore, { myOwnName: 'doubleCounter' }),
				  },
				}
		
		3、监听actions
			const unsubscribe = someStore.$onAction(
			  ({
			    name, 	
			    store, 
			    args, 
			    after, 	  监听actions返回结果后出发
			    onError,  监听actions抛出错误、reject触发
			  }) => {
			    after((result) => {
					...
			    })
			
				onError((error) => {
					...
			    })
			  }
			,true)	第二个参数为true,不会随着组件被卸载而清除
			
			unsubscribe();	手动清除监听
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值