03_Pinia的使用
官网:Pinia | The intuitive store for Vue.js (vuejs.org)
Pinia是一个轻量级的状态管理库。Pinia可以处理大型项目中复杂的状态管理需求,而父传子、子传父以及跨组件通信,可以解决一些简单的状态传递问题。
打开cmd 转到当前项目目录下,安装命令:npm install pinia
修改main.js
import { createApp } from 'vue' //导入Pinia的createPinia方法,用于创建Pinia实例(状态管理库) import { createPinia } from 'pinia' import App from './App.vue' const pinia=createPinia(); const app=createApp(App); app.use(pinia); app.mount('#app');
使用:
添加一个共享的仓库\vuedemo\src\stores\web.js
import { reactive, ref } from 'vue' import { defineStore } from 'pinia' //导出useWebStore export const useWebStore = defineStore('web', () => { //定义一个响应式对象,存储网站信息 const web = reactive({ name: "张三", age: 22 }) //定义一个响应式引用,存储用户数 const users = ref(1000) //定义方法 const userAdd = () => { users.value++ } return { web, users, userAdd } })
app.vue
<script setup> //导入仓库 import { useWebStore } from './stores/web'; const webStore = useWebStore() console.log("webStore.web:",webStore.web) console.log("webStore.users:",webStore.users) </script> <template> {{ webStore.web.name }}----{{ webStore.web.age }}---{{ webStore.users }} <br> <button @click="webStore.userAdd" >添加用户</button> </template> <style scoped> </style>
Pinia数据持久化
官网:Home | pinia-plugin-persistedstate (prazdevs.github.io)
安装命令:npm i pinia-plugin-persistedstate
修改main.js
import { createApp } from 'vue' //导入Pinia的createPinia方法,用于创建Pinia实例(状态管理库) import { createPinia } from 'pinia' //从 pinia-plugin-persistedstate 模块中导入 piniaPluginPersistedstate import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' import App from './App.vue' const pinia=createPinia(); //将插件添加到 pinia 实例上 pinia.use(piniaPluginPersistedstate) const app=createApp(App); app.use(pinia); app.mount('#app');
web.js
import { reactive, ref } from 'vue' import { defineStore } from 'pinia' //导出useWebStore export const useWebStore = defineStore('web', () => { //定义一个响应式对象,存储网站信息 const web = reactive({ name: "张三", age: 22 }) //定义一个响应式引用,存储用户数 const users = ref(1000) //定义方法 const userAdd = () => { users.value++ } return { web, users, userAdd } }, { //持久化存储到 localStorage 中 persist: true })
npm run dev后,点击按钮,然后刷新页面发现webStore.users并没有变化。