文章目录
一、创建项目
npm create vite@latest
二、安装pinia
npm install pinia -S
三、main.ts中引入pinia
import {
createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 导入pinia的hock
import {
createPinia } from 'pinia'
//
const store = createPinia()
const app = createApp(App)
//
app.use(store)
app.mount('#app')
四、初始化store仓库
在src/store/store-name.ts 搞一个枚举用来作为仓库的命名空间
// 用来作为pinia仓库的命名空间
export const enum Names{
TEST = 'TEST'
}
src/store/index.ts
import {
defineStore } from "pinia"
import {
Names } from "./store-name"
export const useTestStore = defineStore(Names.TEST,{
//这里面有三个模块
state: ()=>{
// 将初始化的变量或要用到的变量定义到这里
return {
current: 1,
name: 'kangyun'
}
},
// 类似computed,修饰一些值,也是有缓存的
getters: {
},
// methods,同步异步都可以做,提交state
actions: {
}
})
五、仓库定义好了如何使用呢?
<template>