vue-ssr之nuxt.js的插件使用

摘要:有时候,我们会有这样的需求,在项目的前端页面中需要使用一个swiper插件,来实现图片轮播,但是nuxt是在服务端进行编译的,那么问题来了,我们如何像在vue中那样使用第三方模块,封装轮播公用组件呢?答案是:使用nuxt到插件功能。

有时候,我们会有这样的需求,在项目的前端页面中需要使用一个swiper插件,来实现图片轮播,但是nuxt是在服务端进行编译的,那么问题来了,我们如何像在vue中那样使用第三方模块,封装轮播公用组件呢?答案是:使用nuxt到插件功能。


官方文档:
Nuxt.js允许在实例化Vue.js应用程序之前运行js插件。这在您需要使用自己的库或第三方模块时特别有用。

下面就是一个封装swiper轮播插件到用例。


在nuxt.config.js文件中进行如下配置

...
plugins: [
    { src: ‘~/plugins/swiper.js‘, ssr: false },
    { src: ‘~/plugins/getRequest.js‘, ssr: false },
    { src: ‘~/plugins/rem.js‘, ssr: false },
]
...


在plugins文件夹下新建swiper.js文件,并进行如下编辑

import Vue from ‘vue‘
import ‘swiper/dist/css/swiper.css‘
import VueAwesomeSwiper from ‘vue-awesome-swiper/dist/ssr‘

Vue.use(VueAwesomeSwiper)


在components文件下面新建banner.vue文件,创建组件

<template>
  <div v-swiper:mySwiper="swiperOption">
    <div>
      <div v-for="(item, index) in bannerData" :key="index">
        <img
           
            :src="item.content"
            :bannerSeq="item.bannerSeq"
            :location1="item.location"
            :sequence="item.sequence"
            :remark="item.remark"
            :ga-data="item.buryPoint"
            alt
          >
      </div>
    </div>
    <div></div>
  </div>
</template>

<script>
export default {
  props: ["bannerData"],
  data() {
    return {
      swiperOption: {
        loop: true,
        slidesPerView: "auto",
        centeredSlides: true,
        spaceBetween: 0,
        pagination: {
          el: ".swiper-pagination",
          dynamicBullets: true
        },
        on: {
          slideChange() {
            // console.log("onSlideChangeEnd", this);
          },
          tap() {
            // console.log("onTap", this);
          }
        }
      }
    };
  },
  computed: {},
  created() {
    // 合并用户设置的参数
    this.swiperOption = Object.assign(this.swiperOption, this.options);
  }
};
</script>

<style lang=‘less‘>
</style>

在线项目中使用

<template>
  <div>
    <v-banner :bannerData="bannerData"></v-banner>
  </div>
</template>

<script>
import vBanner from "@/components/web/banner";
export default {
  components: {
    vBanner
  },
  data() {
    return {
      bannerData: {}
    };
  },
  // 获取banner数据
  async asyncData(content) {
    const res = await content.$axios.$post("/api/getFDBanner", { location: "88" });
    if (res.resultCode === "1") {
      return { bannerData: res.resultdata };
    }
  }
};
</script>

<style lang="less">

</style>

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_2056