Hello everyone, recently I am working on a fake ele. me project, I will synchronize my project experience here and share with you!
Vue – Use the Swiper plugin to implement the wheel map
NPM install swiper –save
HTML section of msite.vue:
<! -- Use swiper in the msite_nav navigation section
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">1</div>
<div class="swiper-slide">2</div>
<div class="swiper-slide">3</div>
</div>
<! Swiper -->
<div class="swiper-pagination"></div>
</div>
Copy the code
The script section introduces and initializes:
<script>
import Swiper from 'swiper'
// Import the CSS file for swiper at the same time
import 'swiper/dist/css/swiper.min.css'
export default {
// After the page is mounted, initialize swiper
mounted () {
// Create a swiper instance to implement rotation
new Swiper('.swiper-container', {
autoplay: true.// If you need a pager
pagination: {
el: '.swiper-pagination'.clickable: true
}
})
}
}
</script>
Copy the code
Note that the method of importing the CSS file varies with the version. Otherwise, an error message may be displayed because the corresponding CSS file, such as the latest version, cannot be found
import 'swiper/swiper-bundle.min.css'
Copy the code
[Swiper official document]
One particular note is that you need to create a Swiper instance after the data is requested
Use watch and $nextTick to solve the rotation Bug
-
The pager Swiper should actually be initialized after the rotation list is displayed (that is, the categorys array has data).
-
From the beginning, categorys was an empty array, and the list was displayed only when there was data. To monitor this, watch is used.
// Create watch to listen on categorys watch: { categorys (value) { // There is data in the categorys array // The interface has not been asynchronously updated yet}}// Delete new Swiper in Mounted... code Copy the code
-
However, there are two steps in state, that is, categorys (receiving data) and asynchronous update interface (displaying the list of castings). Wait until the interface is asynchronously updated before you can initialize Swiper.
// Use setTimeout to achieve the effect, but the timing is not accurate setTimeout(() = > { // Create a Swiper instance object to implement rotation new Swiper('.swiper-container', { autoplay: true.// If you need a pager pagination: { el: '.swiper-pagination'.clickable: true}})},100) Copy the code
-
$nextTick([callback]) is used to create a Swiper object as soon as the interface completes an asynchronous update
// Use the data immediately after you modify it, and then wait for DOM updates. this.$nextTick(() = > { // Execute the callback as soon as the interface update is complete new Swiper('.swiper-container', { autoplay: true.pagination: { el: '.swiper-pagination'.clickable: true}})Copy the code
Thank you! Hope to leave your reading traces (likes, concerns, comments) hey hey!