Nuxt3 不再提供 Vuex 集成。推荐使用 pinia
pnpm install pinia @pinia/nuxt
配置 nuxt.config.js
// nuxt.config.js
export default defineNuxtConfig({
// ... 其他配置
modules: [
// ...
'@pinia/nuxt',
],
})
新建 src/store/index.ts
import { defineStore } from 'pinia'
export const useMainStore = defineStore('main', {
state: () => ({
counter: 0,
}),
actions: {
increment() {
// `this` is the store instance
this.counter++
},
},
})
新建 src/store/modules/useUserStore.ts
import { defineStore } from 'pinia'
const USER_INFO = {
userName: '易师傅',
id: 1,
sex: '男',
}
export const useUserStore = defineStore('userInfo', () => {
const userInfo = reactive(USER_INFO)
return {
userInfo,
}
})
使用
<template>
<div>
<strong>
姓名:{{ userInfo.userName }}
性别:{{ userInfo.sex }}
</strong>
</div>
</template>
<script setup lang="ts">
import { useUserStore } from '@/stores'
const userInfo = useUserStore().userInfo
</script>