安装
pnpm add pinia
main.ts引入
import { createPinia } from 'pinia'
app.use(createPinia())
自定义user仓库
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', () => {
const userInfo = ref<{ name: string; password: string } | null>(null)
const isLoggedIn = computed(() => !!userInfo.value)
function login(name: string, password: string) {
userInfo.value = { name, password }
localStorage.setItem('user', JSON.stringify(userInfo.value))
}
function logout() {
userInfo.value = null
localStorage.removeItem('user')
}
function initialize() {
const storedUser = localStorage.getItem('user')
if (storedUser) {
userInfo.value = JSON.parse(storedUser)
}
}
return {
userInfo,
isLoggedIn,
login,
logout,
initialize,
}
})
使用自定义仓库
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/user';
import { onMounted } from 'vue';
const userStore = useUserStore();
const { userInfo, isLoggedIn, login, logout, initialize } = userStore;
onMounted(() => {
initialize();
});
const loginForms = ref()
const loginForm = reactive({
username: 'admin',
password: '123456',
})
const loginDialogVisible = ref(true)
const loginAction = async () => {
console.log('登录按钮被按下' + JSON.stringify(loginForm))
}
</script>