Vue3中使用Pinia(封装并统一导出)
1.创建vue项目
pnpm create vue
npm init vue@latest
2.安装持久化插件
pnpm add pinia-plugin-persistedstate -D
3.mian.js中导出pinia 默认vue已经导入
import './assets/main.css'import { createApp } from 'vue'
import App from './App.vue'
import pinia from "@/store/index";
const app = createApp(App)app.use(pinia)app.mount('#app')
4.创建store目录
user模块
import { defineStore } from "pinia";
import { ref } from "vue";
export const uerStore = defineStore('Big-user', () => {const token = ref('')const token222 = ref('')const userinfo=ref({name:'',age:0})const settoken = (newtoken) => {token.value = newtokentoken222.value = newtoken}const removetoken = () => {token.value = ''}const setuserinfo=()=>{userinfo.value={name:'小明',age:20}}return {token, settoken, removetoken, token222,userinfo,setuserinfo}
}, {persist: true
})
index.js模块
import { createPinia } from 'pinia'
import persist from "pinia-plugin-persistedstate";
const pinia = createPinia()
pinia.use(persist)
export default pinia
export * from './modules/user' // 接收user 模块的所有的按需导出
5.在页面中使用pinia仓库
<script setup>
// 导入仓库 根路径即可
import { uerStore } from "@/store";
// 创建仓库实例
const stores = uerStore()
// 登陆
const loginhandle = () => {stores.settoken('eweee')
}
// 退出
const outhandle = () => {stores.removetoken()
}
// 设置用户信息
const setuseinfohandle = () => {stores.setuserinfo()
}</script><template><div><p>{{ stores.token }}</p><button @click="loginhandle">登陆</button><button @click="outhandle">退出</button><button @click="setuseinfohandle">设置用户信息</button></div>
</template>