没改进之前的效果:
常规思路:button按钮个数写死,绑定点击时间,传参数,实现切换图片效果
<div id="box">
<img :src="imgUrl" alt="图片显示出错">
<button @click="changeImg(0)">One</button>
<button @click="changeImg(1)">Two</button>
<button @click="changeImg(2)">Three</button>
<button @click="changeImg(3)">Four</button>
</div>
<script>
Vue.createApp({
data() {
return {
imgUrl: "./img/jpg/001.jpg", //为什么第一张图片显示不出来
imgList: [
"./img/jpg/001.jpg",
"./img/jpg/002.jpg",
"./img/jpg/003.jpg",
"./img/jpg/004.jpg",
]
}
},
methods: {
changeImg(index) {
this.imgUrl = this.imgList[index];
}
}
}).mount("#box")
</script>
反思:实际开发时,页面就不能写"死",应该动态生成按钮个数。eg:轮播图的小圆点。
改进思路:button按钮个数动态渲染,绑定点击时间,传参数,实现切换图片效果
改进后的HTML5
<div id="box">
<img :src="imgUrl" alt="图片显示出错">
<ul>
<button @click="changeImg(index)" v-for:="(item,index) in imgList">{
{index+1}}</button>
</ul>
</div>
注意(item,index)参数顺序不能写反
改进后的JS代码:增加了一条数据而已
imgList: [
"./img/jpg/001.jpg",
"./img/jpg/002.jpg",
"./img/jpg/003.jpg",
"./img/jpg/004.jpg",
"./img/jpg/005.jpg",//只是增加这一图片数据,无需改动HTML5代码,就会自动生成一个按钮。
]