Nuxt--快速入门 三

373 阅读1分钟

一、content文件夹

content模块读取你项目中的内容/目录,并解析.md、.yml、.csv和.json文件,为你的应用程序创建一个基于文件的CMS。content/ · Nuxt Directory Structure

二、State Management

Nuxt提供了一个useState接口,其返回值是一个ref

对useState的介绍useState · Nuxt Composables

//在composables创建一个一个文件用于存储数据
export const useCounter = () => useState<number>("counter", () => 0);
<script setup>
import { isRef } from "vue";
const count = useCounter();
console.log(isRef(count));
</script>

我们也可以在Vue devTools 看到count是一个Ref

image.png

安装pinia

npm install pinia @pinia/nuxt
//然后在nuxt.config的moudles配置"@pinia/nuxt"

我们创建一个store文件夹下创建一的main.ts

import { defineStore } from "pinia";

// main is the name of the store. It is unique across your application
// and will appear in devtools
export const useMainStore = defineStore("main", {
  // a function that returns a fresh state
  state: () => ({
    counter: 0,
    name: "Eduardo",
  }),
  // optional getters
  getters: {
    // getters receive the state as first parameter
    doubleCounter: (state) => state.counter * 2,
    // use getters in other getters
    doubleCounterPlusOne(): number {
      return this.doubleCounter + 1;
    },
  },
  // optional actions
  actions: {
    reset() {
      // `this` is the store instance
      this.counter = 0;
    },
  },
});

我们可以这样去获取内部的方法和数值

import { useMainStore } from "~/stores/main";
import { storeToRefs } from "pinia";
const main = useMainStore();
// extract specific store properties
const { counter, doubleCounter } = storeToRefs(main);

三、server

server文件会自动扫描一下文件

  • ~/server/api
  • ~/server/routes
  • ~/server/middleware

api下的文件会在接口上自带~/api,如果不需要~/api则放到routes文件夹中

//api下的hello.ts
export default defineEventHandler((event) => {
  return {
    hello: "world",
  };
});

我们在组件中使用$retch()发生请求获取一下

//setup下
const hello = await $fetch("/api/hello");
console.log(hello);

我们可以在api文件夹下面的文件添加一个接口方式的后缀(例如.get)这样有利于RESTful风格,而且这样设置后对应的接口方式只会作用于对应的(.get)后缀文件。