Nuxt3 不再提供 Vuex 集成。推荐使用 pinia

    1. pnpm install pinia @pinia/nuxt

    配置 nuxt.config.js

    1. // nuxt.config.js
    2. export default defineNuxtConfig({
    3. // ... 其他配置
    4. modules: [
    5. // ...
    6. '@pinia/nuxt',
    7. ],
    8. })

    新建 src/store/index.ts

    1. import { defineStore } from 'pinia'
    2. export const useMainStore = defineStore('main', {
    3. state: () => ({
    4. counter: 0,
    5. }),
    6. actions: {
    7. increment() {
    8. // `this` is the store instance
    9. this.counter++
    10. },
    11. },
    12. })

    新建 src/store/modules/useUserStore.ts

    1. import { defineStore } from 'pinia'
    2. const USER_INFO = {
    3. userName: '易师傅',
    4. id: 1,
    5. sex: '男',
    6. }
    7. export const useUserStore = defineStore('userInfo', () => {
    8. const userInfo = reactive(USER_INFO)
    9. return {
    10. userInfo,
    11. }
    12. })

    使用

    1. <template>
    2. <div>
    3. <strong>
    4. 姓名:{{ userInfo.userName }}
    5. 性别:{{ userInfo.sex }}
    6. </strong>
    7. </div>
    8. </template>
    9. <script setup lang="ts">
    10. import { useUserStore } from '@/stores'
    11. const userInfo = useUserStore().userInfo
    12. </script>