1.使用create-vue创建空的项目
2. 创建一个pinia实例(根store)将其传递给应用
pinia添加到项目中
3. pinia实现计数器案例--熟悉基本使用
3.1 常规使用
·创建store
import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('conter', () => {
// 定义数据(state)
const count = ref(0);
//定义修改数据的方法(action:既支持同步也支持异步)
const increment = () => {
count.value++;
};
//必须return,才能提供给组件使用
return {
count,
increment
};
});
·引用创建好的store并使用
<script setup lang="ts">
// 导入use开头的方法
import { useCounterStore } from './stores/counter';
// 执行方法得到实例store对象
const counterStore = useCounterStore();
console.log(counterStore);
</script>
<template>
<button @click="counterStore.increment">{{ counterStore.count }}</button>
</template>
<style scoped></style>
结果:
3.2 使用一个函数(类似于组件setup())来定义一个Store
4 getters实现
5. 定义异步action
渲染一下