Pinia

对比Vuex

  1. Vue3、Vue2都支持

  2. 抛弃Mutations、modules,只有state、getters、action

  3. 完整支持TS

  4. 轻巧、代码简洁

Get Started

  1. install Pinia

    npm init vite
    npm i pinia
  2. use in Vue根组件(main.js)

    import { createPinia } from 'pinia'
    createApp(App).use(createPinia()).mount('#app')
  3. define store/xxx.js

    import { defineStore } from 'pinia'
    import { useOtherStore } from './other'
    
    export const useCounterStore = defineStore('counter', {
    	state: () => {
    		return {
    			helloWorld: 'helloWorld',
    			count: 0,
    			phone: 18088881234,
    		}
    	},
    	//cache
    	getters: {
    		phoneHidden() {
    			return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
    		},
    	},
    	actions: {
    		changeState() {
    			this.count++
    		},
    		getOtherStore() {
    			console.log(useOtherStore().prop)
    		},
        async fillData() {
          this.products = (await import("@/data/product.json")).default
        }
    	},
    })

修改state五种方式

$reset、$subscribe、$onAction

注意

  1. 组件里解构后就丢失响应,需使用storeToRefs

  2. use mapWritableState in stead of mapState

Last updated