vue中swiper的使用(轮播失效)

在使用vue写swiper轮播图的时候,
有时会发生轮播图不生效的问题,
这是因为页面中JS执行的顺序问题,
这时swiper中的Observer(监视器)就派上用场了;

observer:true, // 修改swiper自己或子元素时,自动初始化swiper
observeParents:true, // 修改swiper的父元素时,自动初始化swiper

在swiper中加上这是就可以进行动态监听了,
不过也需要注意的是:swiper应放在vue执行之后
具体代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Swiper demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <link href="https://cdn.bootcss.com/Swiper/4.4.2/css/swiper.css" rel="stylesheet">
    <!-- Swiper JS -->
    <script src="https://cdn.bootcss.com/Swiper/4.4.2/js/swiper.js"></script>
    <!-- 引入veujs -->
    <script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js"></script>
    <style>
        html,body {position:relative;height:100%;}
        body {background:#eee;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;color:#000;margin:0;padding:0;}
        .swiper-container {width:100%;height:100%;}
        .swiper-slide {text-align:center;font-size:18px;background:#fff;display:-webkit-box;display:-ms-flexbox;display:-webkit-flex;display:flex;-webkit-box-pack:center;-ms-flex-pack:center;-webkit-justify-content:center;justify-content:center;-webkit-box-align:center;-ms-flex-align:center;-webkit-align-items:center;align-items:center;}
    </style>
</head>
<body>
<!-- Swiper -->

<div class="vue_ajax" style="height:300px">
    <div class="swiper-container">
        <div class="swiper-wrapper">
            <div class="swiper-slide" v-for="item in posts">
                <!-- <img :src="item" alt=""> -->
                图片{{item}}
            </div>
        </div>
        <div class="swiper-pagination"></div>
    </div>
</div>

<script>
    // ajax 获取数据
    var vm = new Vue({
        el: '.vue_ajax',
        data: {
            posts:['1','2','3','4','5','6','7','8']
        }
    });

    var swiper = new Swiper('.swiper-container', {
        observer:true, // 修改swiper自己或子元素时,自动初始化swiper
        observeParents:true, // 修改swiper的父元素时,自动初始化swiper
        pagination: {
            el: '.swiper-pagination',
        },
    });
</script>
</body>
</html>

冯奎博客
请先登录后发表评论
  • latest comments
  • 总共0条评论