返回

跟着杨村长学 Nuxt 3:每日收获一点点(2)

前端

跟着杨村长的 Nuxt 3 学习之旅仍在继续,让我们深入探索框架的更多功能,每日收获一点点知识。

安装 @pinia/nuxt 插件

Nuxt.js 提供了一个方便的插件,让您可以轻松使用 Pinia 状态管理库。只需运行以下命令:

npm install @pinia/nuxt

安装完成后,在 nuxt.config.ts 文件中注册插件:

import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
  modules: ['@pinia/nuxt'],
})

运行 Nuxt.js 项目

现在,让我们运行我们的 Nuxt.js 项目:

npm run dev

Nuxt.js 将启动一个开发服务器,您可以使用以下网址访问您的应用程序:

http://localhost:3000

Pinia 状态管理

Pinia 是一种轻量级状态管理库,专为 Vue.js 应用程序而设计。它提供了一个响应式的全局存储,允许您在组件之间共享状态数据。

创建一个存储

stores/example.ts 文件中创建一个 Pinia 存储:

import { defineStore } from 'pinia'

export const useExampleStore = defineStore('example', {
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++
    },
  },
})

使用存储

在组件中,您可以使用 useStore() 钩子访问 Pinia 存储:

<script setup>
import { useExampleStore } from '../stores/example'

const store = useExampleStore()
</script>

<template>
  <button @click="store.increment()">Increment</button>
  <p>Count: {{ store.count }}</p>
</template>

踩坑经历

在 StackBlitz 上运行 Nuxt.js Demo

我在 StackBlitz 上运行了 Nuxt.js 演示,但遇到了路由跳转问题。原因是 StackBlitz 使用了一种非标准的路由实现,与 Nuxt.js 默认使用的 Vue Router 不同。

Nuxt.js 无法在 Windows 上运行

另一个陷阱是 Nuxt.js 在 Windows 上运行时会遇到问题。这可能是由于一些依赖项的兼容性问题。我建议使用 WSL(Windows 子系统 for Linux)或 Docker 容器来在 Windows 上开发 Nuxt.js 应用程序。

总结

本文探讨了如何使用 @pinia/nuxt 插件将 Pinia 状态管理添加到 Nuxt.js 项目中。我还分享了一些在 Nuxt.js 中可能遇到的踩坑经历,以及如何解决它们。

跟着杨村长学习 Nuxt 3 的旅程还在继续,期待更多的发现和收获!