vue3引入了新的vue.js状态的管理库,相较与以前的vuex,写法上更简单也更符合vue3的标准:
import { defineStore } from 'pinia'
import {ref} from 'vue
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})
#在需要使用的文件
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
获取count =》 counter.count
获取increment方法,直接counter.increment()
但是,随着定义的状态管理增多,需要多次导入,所以这里记录下统一封装的使用:
1.stores下面定义index.js和modules文件夹分别创建cart.js和user.js
2.这里室stores/index.js的文件内容:
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'
export * from './modules/user'
export * from './modules/cart'
const pinia = createPinia()
pinia.use(persist)
export default pinia
?3.在main.js中引入pinia
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import pinia from './stores/index'
const app = createApp(App)
app.use(pinia)
app.use(router)
app.mount('#app')
4.下面室cart.js和user.js的内容
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
--------------------------------------------------------------
user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore(
'big-user',
() => {
const token = ref('')
const setToken = (data) => {
token.value = data
}
const removeToken = () => {
token.value = ''
}
return {
token,
setToken,
removeToken
}
},
{
persist: true
}
)
5.然后在需要使用的方法就可以直接其定义的变量和方法
import { useUserStore } from '@/stores'
import {userCartStore} from '@stores
const userStore = useUserStore()
const useCart = userCartStore()
#注:pinia的持久化存储的插件?pnpm add pinia-plugin-persistedstate -D
其配置可以参照官方文件,Home | pinia-plugin-persistedstate