上面是最終效果圖~
代碼 (zmd.vue) :
<template>
<el-carousel :interval="4000" type="card" height="200px">
<el-carousel-item v-for="item in imagebox" :key="item.id">
<img :src="item.idView" class="image">
</el-carousel-item>
</el-carousel>
</template>
<script>
export default{
name:'zmd',
data(){
return {
imagebox:[{id:0,idView:require('../assets/imagebox/1.jpg')},
{id:1,idView:require('../assets/imagebox/2.jpg')},
{id:2,idView:require('../assets/imagebox/3.jpg')}
//imagebox是assets下一個放圖片的文件夾
]
}
}
}
</script>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 200px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
別忘了在APP.vue添加import
<script>
import Zmd from './components/zmd.vue'
export default {
name: 'App',
components:{
Zmd
}
}
</script>
保存刷新我們發現圖片的比例似乎和框架不太匹配,這樣每次都要調節圖片大小,很麻煩。接下來我們來調節使圖片自適應。
<template>
<!--動態將圖片輪播圖的容器高度設置成與圖片一致-->
<el-carousel :interval="4000" type="card" height="zmdHeight + 'px'">
<el-carousel-item v-for="item in imagebox" :key="item.id">
<img :src="item.idView" class="image">
</el-carousel-item>
</el-carousel>
</template>
<script>
export default{
name:'zmd',
data(){
return {
imagebox:[{id:0,idView:require('../assets/imagebox/1.jpg')},
{id:1,idView:require('../assets/imagebox/2.jpg')},
{id:2,idView:require('../assets/imagebox/3.jpg')}
],
// 圖片父容器高度
zmdHeight :700,
// 瀏覽器寬度
screenWidth :0
}
},
methods:{
setSize:function () {
// 通過瀏覽器寬度(圖片寬度)計算高度
this.bannerHeight = 400 / 1920 * this.screenWidth;
},
},
mounted() {
// 首次加載時,需要調用一次
this.screenWidth = window.innerWidth;
this.setSize();
// 窗口大小發生改變時,調用一次
window.onresize = () =>{
this.screenWidth = window.innerWidth;
this.setSize();
}
}
}
</script>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 200px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
img{
/*設置圖片寬度和瀏覽器寬度一致*/
width:100%;
height:inherit;
}
</style>
這樣保存刷新之後圖片就很好看了!