Pinia是一个全新的Vue状态管理库,支持vue2.0以及vue3.0(不会受版本印象),支持TypeScript,
vueX,Vuex3(对应Vue2.x) & Vuex4(对应Vue3.x)。
Pinia地址
yarn create @vitejs/app vue3_ts_vite_pinia
Pinia初始化以及使用
安装Pinia
npm i pinia
挂载Pinia
import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';
//状态管理
const pinia = createPinia();
const app = createApp(App);
app.use(pinia)
app.mount('#app')
创建Store
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => {
return {
count: 0,
coolBoy: ['靓女', '靓坤']
}
},
getters: {
findCoolBoy(state) {
// autocompletion! ✨
double: ((state) => state.coolBoy
},
},
actions: {
increment() {
this.count++
},
},
})
调用
import { useCounterStore } from '@/stores'
export default {
setup() {
const counter = useCounterStore()
counter.count++
// with autocompletion ✨
counter.$patch({ count: counter.count + 1 })
// or using an action instead
counter.increment()
},
}
//或者
<script setup lang="ts">
import { useCounterStore } from '@/store';
const store = useCounterStore();
const counts = store;
const store.$patch({ count: counter.count + 1 })
store.increment()
const msg = ref('Hello');
</script>
解构
main.ts
import { useCounterStore } from '@/store';
import { storeToRefs } from 'pinia'
const { count } = storeToRefs(store);
const store = useCounterStore();
//template模板
<template>
<p>Count is {{ store.count }} now</p>
<p>结构数量信息:::{{ count }}</p>
</template>
Getters调用
main.ts
state: () => ({
name: '超级管理员',
count: 0,
}),
getters: {
getCountBuff(state) {
console.log('getters调用同');
return `${state.name}****${state.name}`
},
getMsgWithThis(): string {
console.log('gettersThis调用同');
return `${this.name}****${this.name}`
}
},
index.vue
<h2>Pinia中的Getters</h2>
<p>{{ store.getCountBuff }}</p>
<p>{{ store.getCountBuff }}</p>
<h2>Pinia中的Getters this指向问题</h2>
<p>{{ store.getMsgWithThis }}</p>
<p>{{ store.getMsgWithThis }}</p>
Getters相互调用
store.ts
/**
* 相互调用案例信息
*/
import { defineStore } from 'pinia'
export const allanStore = defineStore({
id: 'store',
state: () => ({
moveList: ['泰坦尼克号', '肖申克的救赎', '阿甘当兵日记', '星际穿越']
}),
getters: {
},
actions: {
},
})
main.ts
import { allanStore } from './store'
getAllanStore(): string[] {
return allanStore().moveList
}
index.vue
<h2>Pinia中的Getters 相互调用</h2>
<ul>
<li v-for="(item, index) in store.getAllanStore" :key="index">{{ item }}</li>
</ul>