官网
npm install pinia@latest
yarn add pinia
配置
1 2 3 4
| import { createPinia } from 'pinia' const pinia = createPinia() app.use(pinia)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import {defineStore} from 'pinia' export const mainStore = defineStore('main',{ state:()=>{ return { message:'hello world!' } }, getters:{ }, actions:{ } })
|
vue模版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| {{store.message}} <script setup> import {mainStore} from '../store/store.js' const store = mainStore() </script> //or <script> import {mainStore} from '../store/store.js' export default{ setup(){ const store = mainStore() return {} } } </script>
|
方法改变变量值
1 2 3 4 5 6 7 8
| <script setup> import { mainStore } from '../store/index' const store = mainStore() const countFun = ()=>{ store.count++ } </script> <button type="button" @click="countFun()">count is: {{ store.count }}</button>
|
解构方法有坑 只能调用默认数据 需要用pinia方法storeToRefs
1 2 3 4 5 6 7 8 9 10
| {{count}} <script setup>
const {count} = store
import {storeToRefs} from 'pinia' const {count} = storeToRefs(store)
</script>
|
四种修改状态数据的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const countFunc=()=>{ store.count++ }
const countFunc2=()=>{ store.$patch({ count:store.count+2, message:'abc' }) }
const countFunc3=()=>{ store.$patch((state)=>{ state.count++; }) }
actions:{ change(){ this.count ==; } }
<button type="button" @click="store.change()">count is: {{ store.count }}</button>
|
1 2 3 4 5 6 7 8 9 10 11
| getters:{ phoneMask(){ return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2') } },
getters:{ phoneMask(state){ return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2') } },
|
仓库之间调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { defineStore } from "pinia"; export const otherStore = defineStore('other',{ state:()=>{ return { list:[1,2,3] } } })
import { otherStore } from './other' actions:{ getList(){ console.log(otherStore().list) } }
store.getList()
|
vue2.+
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import { createPinia, PiniaVuePlugin } from 'pinia' Vue.use(PiniaVuePlugin) const pinia = createPinia()
new Vue({ router, pinia, render: h => h(App) }).$mount('#app')
import { defineStore } from 'pinia' export const mainStore = defineStore('counter', { state: () => ({ personName:'', loadingState:false }), getters: { }, actions: { increment() { }, }, })
import { mainStore } from '@/store/index' data(){ return { store:'', } }, mounted(){ this.store = mainStore() }, methods:{ bindSubmit(){ this.store.loadingState = true } }
|