安装vite
选择vue、TypeScript,其他默认就好
npm create vite@latest
安装Pinia
yarn add pinia# 或者使用 npm install pinia
使用
src/main.ts(注册)
import { createApp } from 'vue'
import store from '@/store';
import './style.css'
import App from './App.vue'
createApp(App).use(store).mount('#app')
src/store/index.ts
import { createPinia } from 'pinia'
const store = createPinia()
export default store
src/store/counter.ts(使用setup模式定义)
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
function increment() {
count.value++;
}
function decrement() {
count.value--;
}
return { count, increment, decrement };
});
组件中使用
<script setup lang="ts">
import { useCounterStore } from '@/store/counter';
const store = useCounterStore();
</script>
<template>
<h1>{{ store.count }}</h1>
<button @click="store.increment">add count</button>
</template>
读取&写入&重置
- 通过定义 一个 store对象,该store不能够被解构,否则会失去响应式(同props),可通过
storeToRefs提取属性同时保持其响应式
<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/store/counter';
const store = useCounterStore();
const { count } = storeToRefs(store);
</script>
<template>
<h1>Demo{{ count }}</h1>
<button @click="store.increment">add count</button>
</template>
批量修改数据
const patchStore = () => {
store.$patch({
name: '张三',
age: 100
});
};
<button @click="patchStore">批量修改数据</button>
整个替换:
store.$state = { name: '33', age: 12, count: 6 };
store之间的相互调用(看以下代码注释)
import { defineStore } from 'pinia';
import { ref } from 'vue';
import {useCartStore} from './cart'; // 其他store
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const name = ref('liming');
const age = ref(0);
const cartStore = useCartStore(); // 在当前store引用其他store
function increment() {
count.value++;
cartStore.changeType();// 调用其他store的方法
}
function decrement() {
count.value--;
}
return { count,age,name, increment, decrement };
});
v-modle
<input v-model="store.count" />
与直接使用vuex区别
- vuex不能直接修改store的数据,需要
commit相关mutations, pinia可以直接修改 - 良好的Typescript支持
- 体积非常小,只有1KB左右。
- pinia 的模块化是通过创建多个独立的 store 实例