1、安装pinia
npm i pinia
2、main.js注册
//导入createPinia
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
//把pinia实例加入app中
app.use(createPinia())
3、创建一个store
创建一个store目录创建index.js
//1.导入pinia
import { defineStore } from 'pinia'
import { ref } from 'vue'
//这是定义一个变量导出pinia这个唯一叫做counter的pinia仓库
export const useCounterStore = defineStore('counter', ()=>{
//2.定义 数据 (state)
const count = ref(0)
//3.定义修改数据的方法 (action,支持同步与异步)
const increment = ()=>{
count.value++
}
// 4.以对象形式返回供组件使用
return {
count,
increment
}
})
4、组件中使用
<script setup>
// 1. 导入use方法
import { useCounterStore } from '@/stores/index'
// 2. 执行方法得到store的实例对象 store里有数据和方法
const counterStore = useCounterStore()
</script>
<template>
//因为获取到了store实例,可以直接调用内部方法与获取内部的数据
<button @click="counterStore.increment">
{{ counterStore.count }}
</button>
</template>
5、getter的使用
按照小兔儿鲜的说法是就是相当于计算属性进行
// 数据(state)
const count = ref(0)
// getter (computed)
const doubleCount = computed(() => count.value * 2)