任意vue项目,我以uniapp为例
官方地址 :pinia github
npm init -y
npm i pinia --save
npm i pinia-plugin-persist --save
pinia-store文件夹名字可以任意起
文件名字可以任意起
index.js
import { createPinia } from 'pinia'
const store = createPinia()
export default store
login.js
import {
defineStore
} from 'pinia'
export const useloginStore = defineStore({
id: 'login', // id必填,且需要唯一
state: () => {
return {
token: '',
userName: '未登录',
}
},
//开启持久化
persist: {
enabled: true,
// storage:sessionStorage/localStorage,还可以自定义如下
// https://seb-l.github.io/pinia-plugin-persist/
// import Cookies from 'js-cookie'
// const cookiesStorage: Storage = {
// setItem (key, state) {
// return Cookies.set('accessToken', state.accessToken, { expires: 3 })
// },
// getItem (key) {
// return JSON.stringify({
// accessToken: Cookies.getJSON('accessToken'),
// })
// },
// }
strategies: [
{ storage: localStorage, paths: ['token','userName'] }
],
},
// actions 用来修改 state
actions: {
login(userName) {
this.userName = userName
this.token = "token-" + userName
},
logout() {
this.userName = '已退出登录'
this.token = ''
}
}
})
import App from './App'
// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App,
})
app.$mount()
// #endif
// #ifdef VUE3
import {
createSSRApp
} from 'vue'
// vuex
import store from './store'
// pinia
import pstore from './pinia-store'
//pinia持久化
import piniaPersist from 'pinia-plugin-persist'
export function createApp() {
const app = createSSRApp(App)
pstore.use(piniaPersist)
app.use(pstore)
app.use(store)
return {
app
}
}
// #endif
<template>
<view>
<view>
<button type="primary" @click="login('刘大根')">登录</button>
<button type="default" @click="logout">退出</button>
</view>
<!-- <view>{{userName}}</view> -->
<view>{{loginStore.userName}}</view>
</view>
</template>
<script>
// import store from '@/store/index.js'
// import {
// mapActions,
// mapState
// } from 'vuex'
import { useloginStore } from '@/pinia-store/login'
const loginStore = useloginStore()
export default {
data() {
return {
loginStore:loginStore
}
},
computed: {
// ...mapState(['userName'])
},
methods: {
// ...mapActions(['login','logout'])
login(userName){
loginStore.login(userName)
},
logout(){
loginStore.logout()
}
}
}
</script>