Swiper.js轮播图插件用Vue封装成简单的组件示例
应用场景
Swiper在Vue中的运用,一般是封装成一个组件。原因是Swiper对象的初始化以及模块化开发。
代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swiper封装,单一页面</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css" />
<script src="https://unpkg.com/swiper/swiper-bundle.js"></script>
<style>
.swiper-container {
width: 100vw;
height: 100px;
}
</style>
</head>
<body>
<main id="root">
<swiper-component :key="list.length">
<div class="swiper-slide" v-for="name in list">
{{ name }}
</div>
</swiper-component>
</main>
<template id="swiper-component-template">
<section>
<div class="swiper-container">
<div class="swiper-wrapper">
<slot></slot>
</div>
<div class="swiper-pagination"></div>
</div>
</section>
</template>
<script>
new Vue({
el: "#" + "root",
data: {
list: [
"阮中楠", "雷文龙", "蔡德东",
],
},
components: {
"swiper-component": {
template: "#" + "swiper-component-template",
mounted() {
new Swiper(".swiper-container", {
loop: true,
pagination: {
el: ".swiper-pagination",
},
});
},
},
},
});
</script>
</body>
</html>
代码写法解释
为什么要额外写一个.swiper-container类选择器?
这里的目的是为了让Swiper的html结构有一个初始化的大小,这种写法是参照Swiper的API文档所写的。核心目的是,让具有.swiper-container类的div标签具有一个合适的大小。因此这里还可以写成其他的css选择器。
为什么swiper-component组件要加上一个key值?
在实际运用时,数据可能是异步传输的,在数据更新不及时时,利用Vue.js的diff算法来对组件进行更新,就可以实现数据依赖式的页面更新。这同时也是为了让Swiper对象重新初始化的方式。
为什么Swiper对象的初始化在组件的mounted周期内?
在组件Vue对象被挂载到html结构时,此时的dom结构已经生成,而Swiper对象的初始化前提是必须要先生成dom结构。根据Swiper初始化的特点,所以写在该组件的mounted生命周期内。
该写法的使用缺陷
该组件向外开放了slot插槽,这个插槽填参的写法必须加上.swiper-slide类,否则无法被Swiper所识别。