当前位置: 首页 > news >正文

Nuxt 入门实战 - 05:特性

自动导入

说明:以下目录只要有引用,都具有自动导入能力

  • components:可以被template 直接使用
  • composables:其中的导出,可以直接被template、ts、js 文件直接引用使用
  • utils:其中的导出,可以直接被template、ts、js 文件直接引用使用

拉取数据

<script setup>
const { data } = await useFetch('/api/hello')
</script><template><div><p>Result of <code>/api/hello</code>:</p><pre>{{ data }}</pre><p><NuxtLink to="/external">Visit /external</NuxtLink></p><p><NuxtLink to="/component">Visit /component</NuxtLink></p></div>
</template>

状态共享

说明:此时counter 和 sameCounter 就共用一个状态了

//app.vue
<script setup>
//1.赋值
const counter = useState("counter", () => 30);
//2.获取共享状态
const sameCounter = useState("counter");
</script><template><div><p>Counter: {{ counter }}</p><p><button @click="counter--">-</button><button @click="counter++">+</button></p><p>Same Counter: {{ sameCounter }}</p><Test></Test></div>
</template>

Meta Tags

说明:可以在页面template中添加html head 内容,修改页面head数据

<template><div><p>We are using renderless <code>&lt;Html&gt;</code>,<code>&lt;Meta&gt;</code>, <code>&lt;Title&gt;</code> components<br />that can magically bind the meta inside Vue components.</p><Html lang="en"><Head><Title>Lucky number: {{ number }}</Title><Meta name="description" :content="`My page's ${number} description`" /></Head></Html><p><button @click="number = Math.round(Math.random() * 100)">Click me and see the title updates</button></p><p><NuxtLink to="/about">About page</NuxtLink></p></div>
</template>

Layout

  • NuxtLayout 默认引用Layouts/default.vue 布局

  • NuxtLink 相当于router-link

  • 动态修改layout

    setPageLayout(layoutname)
    
  • 导航进特定路由前,执行中间件

    //pages/other.vue
    <script setup>
    definePageMeta({middleware: 'other'
    })
    </script>
    

    进入other路由器,会先执行middleware/other.ts 中间件

    //middleware/other.ts
    export default defineNuxtRouteMiddleware(() => {setPageLayout('other')
    })
    

routing

  • 禁止跳转进某个路由

    //pages/fobidden.vue
    <template><div>Forbidden</div>
    </template><script setup>
    definePageMeta({middleware: () => {console.log("Strictly forbidden.");//! 返回false,可禁止跳入此路由return false;},
    });
    </script>
    
  • 利用middleware 重定向

    //pages/redirect.vue
    <template><div>You should never see this page</div>
    </template><script setup>definePageMeta({middleware: 'redirect-me'
    })
    </script>
    
    //middleware/redirect-me.ts
    export default defineNuxtRouteMiddleware((to) => {const { $config } = useNuxtApp()if ($config) {console.log('Accessed runtime config within middleware.')}console.log('Heading to', to.path, 'but I think we should go somewhere else...')return '/secret'
    })
    
  • 全局中间件:只要切换路由就会执行

    //middleware.global.ts
    export default defineNuxtRouteMiddleware(() => {console.log('running global middleware')
    })
    
  • 获取当前路由信息

    const route = useRoute()
    
  • 路由占位符传参

    //app.vue
    <button class="n-link-base" @click="$router.push(`/parent/reload-${(Math.random() * 100).toFixed()}`)">Keyed child
    </button>
    

    说明:会先加载parent组件,然后通过parent再嵌套载入reload-[id].vue 组件,会将reload-后面的参数动态传给reload-[id].vue 组件

NuxtLink 相当于 router-link,NuxtPage 相当于 router-view

配置extend

  • nuxt.config.ts 继承

    //nuxt.config.ts
    export default defineNuxtConfig({extends: ['./ui','./base'],runtimeConfig: {public: {theme: {primaryColor: 'user_primary'}}},modules: ['@nuxt/ui']
    })
    

    app.config.ts 也会自动继承

    export default defineAppConfig({foo: 'user',bar: 'user',baz: 'base',array: ['user','user','user']
    })
    
  • base 配置

    //base/nuxt.config.ts
    export default defineNuxtConfig({imports: {dirs: ['utils']},runtimeConfig: {public: {theme: {primaryColor: 'base_primary',secondaryColor: 'base_secondary'}}}
    })
    
    export default defineAppConfig({bar: 'base',baz: 'base',array: () => ['base','base','base'],arrayNested: {nested: {array: ['base','base','base']}}
    })
    

最终nuxt.config.ts 和app.config.ts 都会对应合并

错误处理

  • 通过插件捕获错误

    //plugins/error.ts
    export default defineNuxtPlugin((nuxtApp) => {nuxtApp.hook('vue:error', (..._args) => {console.log('vue:error')// if (process.client) {//   console.log(..._args)// }})nuxtApp.hook('app:error', (..._args) => {console.log('app:error')// if (process.client) {//   console.log(..._args)// }})//全局错误处理nuxtApp.vueApp.config.errorHandler = (..._args) => {console.log('global error handler')// if (process.client) {//   console.log(..._args)// }}
    })
    
  • 中间件处理错误

    //middleware/error.global.ts
    export default defineNuxtRouteMiddleware((to) => {if ('middleware' in to.query) {return showError('error in middleware')}
    })
    

说明:根目录创建error.vue,出错就会跳转至此页面,错误消息通过defindPros 中的error.message拿到

module

可以将页面拓展到模块,然后extendPages接口将拓展的页面加进路由中

  1. 配置nuxt.config.ts 添加对应模块

    //nuxt.config.js
    export default defineNuxtConfig({modules: ['~/modules/pages/index','@nuxt/ui']
    })
    
  2. setup添加模块页面

    //modules/pages/index.ts
    import { defineNuxtModule, extendPages } from '@nuxt/kit'
    import { resolve } from 'pathe'export default defineNuxtModule({setup () {extendPages((pages) => {// Add /test pagepages.push({name: 'Test',path: '/test',file: resolve(__dirname, './pages/test.vue')})})}
    })
    

Cookie

//默认为空,具备响应式
const user = useCookie<{ name: string }>('user')
const logins = useCookie<number>('logins')

更多

最近我开源了一个文章助手artipub,可以帮你一键将markdown发布至多平台,方便大家更好的传播知识和分享你的经验。
官网地址:https://artipub.github.io/artipub/ (提示:国内访问可能有点慢,翻墙就会很快)

帮忙点个star⭐,让更多人知道这个工具,谢谢大家🙏。如果你有兴趣,欢迎加入你的加入,一起完善这个工具。

参考文献

  • https://nuxt.com/docs/examples/features/auto-imports
  • https://nuxt.com/docs/examples/features/data-fetching
  • https://nuxt.com/docs/examples/features/state-management
  • https://nuxt.com/docs/examples/features/meta-tags
  • https://nuxt.com/docs/examples/features/layouts
  • https://nuxt.com/docs/examples/routing/middleware
  • https://nuxt.com/docs/examples/routing/pages
  • https://nuxt.com/docs/examples/advanced/config-extends
  • https://nuxt.com/docs/examples/advanced/error-handling

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • vue项目中scss文件导出,js文件引入scss文件时为空{}
  • 代码随想录 -- 哈希表 -- 三数之和
  • Django 框架中F和Q的作用
  • 富格林:极力破除欺诈维护安全
  • 以太网PHY驱动调试笔记(KSZ8081)
  • 代码随想录算法day25 | 贪心算法part03 | 134. 加油站,135. 分发糖果,860.柠檬水找零,406.根据身高重建队列
  • 算法学习-基础数据结构
  • 【python】懂车帝字体反爬逐层解密案例(附完整代码)
  • 中秋佳节,数码好礼伴团圆:中秋节五大数码礼品指南
  • docker compose用法详解
  • 深度确定问题中的树森林操作:分析与实现
  • OpenCV+Python识别机读卡
  • 盘点国内外最好用的12款源代码加密软件:总有一款适合你
  • Python爬虫,爬取某网站小说
  • Nvidia财报前夕:市场预期股价波动创纪录,AI芯片巨头引领市场热潮
  • 2018以太坊智能合约编程语言solidity的最佳IDEs
  • Babel配置的不完全指南
  • create-react-app项目添加less配置
  • create-react-app做的留言板
  • ES6语法详解(一)
  • JavaScript 奇技淫巧
  • javascript面向对象之创建对象
  • js中forEach回调同异步问题
  • Laravel 实践之路: 数据库迁移与数据填充
  • macOS 中 shell 创建文件夹及文件并 VS Code 打开
  • Redis学习笔记 - pipline(流水线、管道)
  • SegmentFault 技术周刊 Vol.27 - Git 学习宝典:程序员走江湖必备
  • 聚类分析——Kmeans
  • 全栈开发——Linux
  • 融云开发漫谈:你是否了解Go语言并发编程的第一要义?
  • 如何解决微信端直接跳WAP端
  • 深入浏览器事件循环的本质
  • 新手搭建网站的主要流程
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • Java数据解析之JSON
  • ​​​【收录 Hello 算法】9.4 小结
  • ​业务双活的数据切换思路设计(下)
  • #100天计划# 2013年9月29日
  • (2.2w字)前端单元测试之Jest详解篇
  • (DFS + 剪枝)【洛谷P1731】 [NOI1999] 生日蛋糕
  • (el-Date-Picker)操作(不使用 ts):Element-plus 中 DatePicker 组件的使用及输出想要日期格式需求的解决过程
  • (二)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (附源码)php投票系统 毕业设计 121500
  • (三分钟)速览传统边缘检测算子
  • (十八)Flink CEP 详解
  • (十二)devops持续集成开发——jenkins的全局工具配置之sonar qube环境安装及配置
  • (十二)springboot实战——SSE服务推送事件案例实现
  • (图文详解)小程序AppID申请以及在Hbuilderx中运行
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • (轉貼) UML中文FAQ (OO) (UML)
  • .\OBJ\test1.axf: Error: L6230W: Ignoring --entry command. Cannot find argumen 'Reset_Handler'
  • .bat批处理(四):路径相关%cd%和%~dp0的区别
  • .Net Core 生成管理员权限的应用程序
  • .NET 设计模式初探
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)