Published: 31 May 2023 › Updated: 31 May 2023

Nuxt中间件和插件 / nuxt#6
中间件
middleware 目录,Nuxt提供了一个可定制的路由中间件框架,可以在整个应用程序中使用,非常适合在导航到特定路由之前提取想要运行的代码。
//middleware -> search.js
export default defineNuxtRouteMiddleware((to,from)=>{
const { type,page } = to.params
const { keyword } = to.query
if(!keyword){
return abortNavigation("搜索关键词不能为空")
}
if(!(["course","column"].includes(type)) || isNaN(+page)){
return abortNavigation("页面不存在")
}
})
//index.vue
definePageMeta({
middleware:["search"]
})
//eg2
//中间件可以获取目标路由 to 和来源路由 from,还有两个很常用的工具方法:
abortNavigation(error):跳过,留在 from;
navigateTo(route):指定跳转目标。
export default defineNuxtRouteMiddleware((to, from) => {
if (to.params.id === '1') {
return abortNavigation()
}
return navigateTo('/')
})
//全局中间件
//命名时带上 global
middleware -> search.global.js
另外,中间件全名不能使用小驼峰的方法,要使用 `-` !
插件
1. plugins/目录 -> myPlugin.ts
2. myPlugin.ts
export default defineNuxtPlugin(nuxtApp => {
// Doing something with nuxtApp
})
export default defineNuxtPlugin(() => {
return {
provide: {
hello: (msg: string) => `Hello ${msg}!`
}
}
})
<template>
<div>
{{ $hello('world') }}
</div>
</template>
<script setup lang="ts">
// alternatively, you can also use it here
const { $hello } = useNuxtApp()
</script>
eg: 全局加载条
import {
createDiscreteApi
} from "naive-ui"
export default defineNuxtPlugin((nuxtApp)=>{
const bar = ref(null)
nuxtApp.hook("app:mounted",(e)=>{
if(!bar.value){
const { loadingBar } = createDiscreteApi(["loadingBar"])
bar.value = loadingBar
}
// console.log(6688, "app:mounted")
})
nuxtApp.hook("page:start",(e)=>{
bar.value?.start()
// console.log("page:start")
})
nuxtApp.hook("page:finish",(e)=>{
setTimeout(() => {
bar.value?.finish()
}, 150)
// console.log(6699, "page:finish")
})
nuxtApp.hook("app:error",(e)=>{
// console.log("app:error");
if(process.client){
setTimeout(() => {
bar.value?.finish()
}, 150)
}
})
})
又是几个自动注入的工具!在Nuxt中开发时,确实有种很方便的感觉。找到它对应的语法,几条语句就可实现很强大的功能!
Leave Nuxt中间件和插件 / nuxt#6 to:
Read more #cn posts
Best Posts From lemooljiang
We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.