Nuxt3项目实战篇9——Nuxt3中插件的使用
2022-07-29 14:10:32
上一篇我们学习了head的设置, SEO都做好了。 这一篇将学习Nuxt3的插件的开发与使用。那烦人的document is not definided, window is not definided怎么解决。 学习完了这一篇,你会得到完美的答案。
plugins下的文件二级目录的js/ts文件不会被注册为插件, 只有目录顶层的文件才会被注册为插件。还有,Nuxt3将自动读取你plugins目录中的文件并加载它们。你可以在文件名中使用.server或.client后缀以仅在服务器或客户端加载插件。
Nuxt3中使用defineNuxtPlugin注册插件:
export default defineNuxtPlugin(nuxtApp => { // Doing something with nuxtApp })
我们手动创建插件。 创建一个对象,在里面设置providekey,比如:
//plugins/hello.js export default defineNuxtPlugin(() => { return { provide: { hello: (msg: string) => `Hello ${msg}!` } } })
//pages/index.vue <template> <div> {{ $hello('world') }} </div> </template> <script setup lang="ts"> // alternatively, you can also use it here const { $hello } = useNuxtApp() </script>
二、 使用第三方插件。 我们以vue-awesome-swiper为例
// pligins/swiper.js import { defineNuxtPlugin } from "#app"; import VueAwesomeSwiper from 'vue-awesome-swiper' import 'swiper/css' import 'swiper/css/pagination' // 文档 // https://github.surmon.me/vue-awesome-swiper export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(VueAwesomeSwiper); });
<swiper class="swiper swiper-home" :modules="modules" :slides-per-view="1" :mousewheel="true" :direction="'vertical'" :auto-height="true" @swiper="setVSwiperRef" @slide-change="updateVSwiperIndex" > <swiper-slide class="slide slide-page slide1"></div> <swiper-slide class="slide slide-page slide1"></div> <swiper-slide class="slide slide-page slide1"></div> </swiper> <script setup> import { Pagination, Navigation, Mousewheel } from 'swiper' // 获取swiper实例 let vSwiperRef = null const setVSwiperRef = (swiper) => { vSwiperRef = swiper } const vSwiperIndex = ref() const updateVSwiperIndex = () => { vSwiperIndex.value = indexData[vSwiperRef?.activeIndex].lowerCase } //点击进行prev/next切换 const nextVSwiperSlide = () => vSwiperRef?.slideNext() const prevVSwiperSlide = () => vSwiperRef?.slidePrev() const scrollTo = (name, index) => { return vSwiperRef?.slideTo(index) } const modules = [Pagination, Navigation] </script>
Nuxt3中使用vue-awesome-swiper这个插件,是我研究了很久实现的功能。所以代码贴得也多了些。
Nuxt3中提示window is not definided/document is not definided。 这个问题,在nuxt2中是直接在nuxt.config.js的plugins下写ssr:false。 在Nuxt3中,官方的说辞是给在文件后面添加.client后缀表示该插件仅仅在客户端进行渲染, 例如:test.client.js,