vue-动态渲染数据(this.$nextTick) & swiper 组件

在 mounted 钩子里,不能根据数据改变而改变
如果放在 updated 钩子里,随便一个数据发生改变,都会重新生成补丁对象
但每次都实例化,这样是肯定不行的
所以有了 $nextTick

nextTick表示所有的真实dom渲染结束之后执行

this.$nextTick(() => { })
<template>
  <div class="swiper-container">
<input type="text" v-model ="num">
      <div class="swiper-wrapper">
          <div class="swiper-slide"
            v-for = "item in banners"
            :key = "item.id"
          >
            <img :src = "item.img" alt="">
          </div>
      </div>
      <!-- 如果需要分页器 -->
      <div class="swiper-pagination"></div>
      
      <!-- 如果需要导航按钮 -->
      <div class="swiper-button-prev"></div>
      <div class="swiper-button-next"></div>
      
      <!-- 如果需要滚动条 -->
      <div class="swiper-scrollbar"></div>
  </div>
</template>

<script>
import Swiper from 'swiper'
/* swiper使用要求真实DOM必须存在 */
export default {
  data () {
    return {
      banners: [],
      num: 100
    }
  },
  mounted () {
    fetch('/mock/banner.json')
      .then( res => res.json())
      .then( data => {
        this.banners = data 
        this.$nextTick(() => {
          /* nextTick表示所有的真实dom渲染结束之后执行 */
            var mySwiper = new Swiper ('.swiper-container', {
              loop: true, // 循环模式选项
              autoplay: true,
              // 如果需要分页器
              pagination: {
                el: '.swiper-pagination',
              },
              
              // 如果需要前进后退按钮
              navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
              },
              
              // 如果需要滚动条
              scrollbar: {
                el: '.swiper-scrollbar',
              },
            }) 
        })
      }).catch( err => console.log( err ))
      
  },
  updated () {
    /* 组件内其他数据改变会重复实例化问题 */
    // console.log('updated')
    // var mySwiper = new Swiper ('.swiper-container', {
    //   loop: true, // 循环模式选项
    //   autoplay: true,
    //   // 如果需要分页器
    //   pagination: {
    //     el: '.swiper-pagination',
    //   },
      
    //   // 如果需要前进后退按钮
    //   navigation: {
    //     nextEl: '.swiper-button-next',
    //     prevEl: '.swiper-button-prev',
    //   },
      
    //   // 如果需要滚动条
    //   scrollbar: {
    //     el: '.swiper-scrollbar',
    //   },
    // })   
  }
}
</script>

<style lang="stylus" scoped>
  .swiper-container 
    width 600px 
    height 300px 
</style>

其中用上了swiper组件

Swiper


安装:

yarn add swiper

然后就能直接用了,在组件中

import Swiper from 'swiper'

其中注意点:swiper使用要求真实DOM必须存在

引入swiper的样式:(在入口文件main.js中引入)

import 'swiper/css/swiper.css'
发布了55 篇原创文章 · 获赞 8 · 访问量 1768

猜你喜欢

转载自blog.csdn.net/louting249/article/details/103132583