在 Vue 中使用 Swiper Element (WebComponent)

知道这个套件一阵子了,但有一天要使用他的时候被官方文件写的这段话吓到。

Swiper Vue components will likely to be removed in future versions. It is recommended to migrate to Swiper Element instead.

于是依照他的建议使用了WebComponent导入专案
先照着官方文件的步骤来安装吧!

安装

下载套件
$ npm install swiper 
当您从节点模块导入 Swiper 自定义元素时,我们需要手动注册它。它应该只执行一次,并且它会在全局範围内注册 Swiper 自定义元素。(看起来是要在main.js当中注册它)
// main.jsimport { register } from 'swiper/element/bundle';const app = createApp(App);app.use(register);app.mount('#app');

假如今天没有要用Vue可以直接

// 来自 CDN 的 Swiper 自定义元素<script src="https://cdn.jsdelivr.net/npm/swiper@9/swiper-element-bundle.min.js"></script>

这种情况会自动注册,不需要调用register()

模板中使用
// 任何.vue档案<template>    <!-- 使用pagination功能 -->    <swiper-container pagination="true">        <swiper-slide>            <img :src="图片src绑定的资料" alt="">        </swiper-slide>        <swiper-slide>            <img :src="图片src绑定的资料" alt="">        </swiper-slide>    </swiper-container></template>

到这边文档还是看的懂,而且可以正常使用
但刺激的来了,浏览器开始跳出一堆
Failed to resolve component
大意是虽然注册成为全域的 Custom Element ,但是这样 Vue 并不知道这个 Custom Element 的存在,所以要去 vue.config.js 设定让 webpack 在编译的时候可以看的懂

开始修改

vue.config.js底下新增这段语法

module.exports = {  chainWebpack: config => {    config.module      .rule('vue')      .use('vue-loader')      .tap(options => ({        ...options,        compilerOptions: {          // 将所有带 swiper- 的标籤名都视为自定义元素          isCustomElement: tag => tag.startsWith('swiper-')        }      }))  }}

终端机重新执行npm run surve
那段讨厌的警告就消失了


补充更改样式

邪教派
直接在sass中这样写..
:root {    --swiper-theme-color: #9747ff;    --swiper-pagination-bottom: 0px;}
官方文件教的
  const swiperEl = document.querySelector('swiper-container');  const params = {    // 直接写要更改的CSS样式    injectStyles: [      `      :host(.red) .swiper-wrapper {        background-color: red;      }      `,    ],    // 可以汇入css档案    injectStylesUrls: ['path/to/one.css', 'path/to/two.css'],  };  Object.assign(swiperEl, params);  // 初始化  swiperEl.initialize();

提供给跟我一样迷茫的旅人,如果有理解错的地方欢迎纠正!


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章