安装Pinia
npm install pinia
main.js
import { createApp } from 'vue'
//导入Pinia的createPinia方法,用于创建Pinia实例(状态管理库)
import { createPinia } from 'pinia'
import App from './App.vue'
//创建一个Pinia实例,用于在应用中集中管理状态(store)
const pinia = createPinia()
//createApp(App).mount('#app')
const app = createApp(App)
app.use(pinia) //将Pinia实例注册到Vue应用中
app.mount('#app')
web.js
import { reactive, ref } from 'vue'
import { defineStore } from 'pinia'
/*
定义一个基于 Pinia 的 Store
第1个参数 web 是 useWebStore 在应用中的唯一标识符(ID)
第2个参数是 Setup函数 或 Option对象
*/
export const useWebStore = defineStore('web', () => {
//定义一个响应式对象,存储网站信息
const web = reactive({
title: "邓瑞编程",
url: "dengruicode.com"
})
//定义一个响应式引用,存储用户数
const users = ref(1000)
//定义方法
const userAdd = () => {
users.value++
}
return {
web,
users,
userAdd
}
})
App.vue
<script setup>
import { useWebStore } from './stores/web.js'
const webStore = useWebStore()
console.log("webStore.web:",webStore.web)
console.log("webStore.users:",webStore.users)
</script>
<template>
{{ webStore.web.url }}
{{ webStore.users }}
<button @click="webStore.userAdd" >添加用户</button>
</template>
<style scoped>
</style>