分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

Nuxt.js + koa2 入门

发布时间:2023-09-06 02:22责任编辑:赖小花关键词:js

1. nuxt项目初始化

$ vue init nuxt-community/koa-template <project-name>$ cd <project-name>$ npm run dev<!-- ???1. 如果有报错: Plugin/Preset files are not allowed to export objects, only functions ???????需要降低nuxt版本至1.4.2: ???????npm uninstall nuxt ???????npm install nuxt@1.4.2 ???????????2. ?升级eslint-plugin-html ????????$ npm i eslint-plugin-html@^3-->

2. 新建路由

(创建即配置)在pages目录中新建一个vue文件,即成功创建了路由,文件名也就是路由名称。

3. 模板文件

layouts 目录下的所有文件都属于个性化布局文件,可以在页面组件中利用 layout 属性来引用。
请确保在布局文件里面增加 组件用于显示页面非布局内容。
举个例子:

新建:layouts/search-layout.vue:

<template> ?<div> ???<h1>search page</h1> ???<nuxt/> ???<footer>这是一个自定义的只用于search的模板</footer> ?</div></template><script>export default {}</script>

在 pages/search.vue 里, 可以指定页面组件使用 search-layout 布局。

<template> ?<div> ???<h2>search page</h2> ?</div></template><script>export default { ?layout: 'search-layout'}</script> ?

4. 全局配置文件:nuxt.config.js

这里面定义了所有页面的head title 和main.css 。。。等

5. 接口路由配置

5.1 在server目录新建interface/city.js

import Router from 'koa-router'const router = new Router({ ?prefix: '/city'})router.get('/list', async (ctx) => { ?ctx.body = { ???list: ['北京', '上海', '菏泽'] ?}})export default router

5.2 在server/index.js中引入新建路由

import Koa from 'koa'import { Nuxt, Builder } from 'nuxt'// 引入新建接口路由import cityInterface from './interface/city'
// 使用新建接口路由app.use(cityInterface.routes()).use(cityInterface.allowedMethods())

访问:http://localhost:3000/city/list 验证是否成功

5.3 从新建接口中获取数据

<template> ?<div> ???<h2>search page</h2> ???<ul> ?????<li v-for="(item, index) in list" :key="index"> ???????{{item}} ?????</li> ???</ul> ?</div></template><script>import axios from 'axios'export default { ?layout: 'search-layout', ?data() { ???return { ?????list: ['11', '22', '33'] ???} ?}, ?async mounted() { ???let res = await axios.get('/city/list') ???console.log(res) ???this.list = res.data.list ?}}</script>

参考

  • https://github.com/nuxt-community/koa-template
  • https://zh.nuxtjs.org/guide/async-data
  • https://www.jianshu.com/p/840169ba92e6

Nuxt.js + koa2 入门

原文地址:https://www.cnblogs.com/cckui/p/9964171.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved