npm create vite@latest
然后按照提示操作即可!
npm install pinia --save
新建 src/store 目录并在其下面创建 index.js,导出 store
// src/store/index.js
import { createPinia } from 'pinia'
const store = createPinia()
export default store
import { createApp } from 'vue'
import store from './store'
import App from './App.vue'
const app = createApp(App)
app.use(store)
app.mount('#app')
在 src/store 下面创建一个user.js
//src/store/user.js
import { defineStore } from 'pinia'
export const userStore = defineStore({
id: 'user',
state: () => {
return {
userName: 'user'
}
}
})
<template>
<div>{{ user.userName}}</div>
</template>
<script setup>
import { userStore} from '@/store/user'
const user = userStore()
</script>
<template>
<div>{{ userName}}</div>
</template>
<script setup>
import { userStore} from '@/store/user'
const user = userStore()
const userName= computed(() => user.userName)
</script>
<template>
<div>{{ userName }}</div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { userStore} from '@/store/user'
const user = userStore()
let { userName } = storeToRefs(user)
</script>
import {userStore} from '@/store/user'
const user = userStore()
user.userName = "王五"
import {userStore} from '@/store/user'
const user = userStore()
user.$patch((state) => {
state.userName = "王五"
})
import {userStore} from '@/store/user'
const user = userStore()
user.$state = { userName: "王五" }
//src/store/user.js
import { defineStore } from 'pinia'
export const userStore = defineStore({
id: 'user',
state: () => {
return {
userName: 'user'
}
},
actions: {
updateUserName(userName) {
this.userName= userName
}
}
})
<script setup>
import {userStore} from '@/store/user'
const user = userStore()
user.updateUserName('王五')
</script>
import {userStore} from '@/store/user'
const user = userStore()
user.$subscribe((arg, state) => { //需要写在数据变化前面
console.log('subscribe', arg, state)
})
user.updateUserName('王五')
</script>
import {userStore} from '@/store/user'
const user = userStore()
user.$onAction((arg) => { //监听方法调用
console.log('onAction', arg)
})
user.updateUserName('王五')
</script>
插件 pinia-plugin-persist 可以辅助实现数据持久化功能。
npm i pinia-plugin-persist --save
// src/store/index.js
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export default store
接着在对应的 user.js 里配置即可
//src/store/user.js
import { defineStore } from 'pinia'
export const userStore = defineStore({
id: 'user',
state: () => {
return {
userName: 'user'
}
},
actions: {
updateUserName(userName) {
this.userName= userName
}
},
// 开启数据缓存
persist: { //数据默认存在 sessionStorage 里,并且会以 store 的 id 作为 key
enabled: true
}
})
persist: {
enabled: true,
strategies: [
{
key: 'user',
storage: localStorage,
}
]
}
本次分享到这里就结束了,感谢您的阅读,如果本文对您有什么帮助,别忘了动动手指点个赞❤️