代码部分
在html文件中引入vue.js
创建一个vue实例,将其绑定到HTML文件中的一个div元素上
.在Vue 实例的data 选项中定义了一个数组imgs,其中包含了一组图片的地址。
var VM = new Vue({
el: "#app",
data: {
imgs: ["R-C-(1)_01.jpg",
4.在HTML文件中定义了一个名为“tempContent"的模板,该模板用来描述一个图片组件的样式。
<template id="tempContent">
<div class="item" @click="c1">
<img
:src="im"
:style="{ display: show ? 'block' : 'none' }"
class="img"
/>
<div
class="placeholder"
:style="{ display: show ? 'none' : 'block' }"
></div>
</div>
</template>
5.通过Vue.component方法定义了一个名为“test-div"的全局组件,它使用上述模板作为其模板,props属性定义了一个名为“im”的属性,用于接收图片地址。组件中定义了一个data 属性show,用于表示图片是否显示,定义了一个c1方法,用于切换图片的显示:
Vue.component("test-div", {
template: "#tempContent",
props: ["im"], //自定义属性
data: function () {
return {
show: true,
};
},
methods: {
c1: function () {
this.show = !this.show;
},
},
});
6.在HTML文件中使用自定义组件test-div』并使用v-for 指令循环渲染imgs数组中的所有图片,生成多个图片组件。
<test-div v-for="img in imgs" :im="img" :key="img"></test-div>
7.在CSS样式表中定义了图片组件的样式,包括宽度、高度、边框、居中等。
.content {
width: 1000px;
border: 1px solid red;
margin: 0 auto;
/*弹性布局*/
display: flex;
/*在主轴上的对齐方式*/
justify-content: space-around;
/*是否换行*/
flex-wrap: wrap;
}
.item {
height: 50px;
width: 80px;
margin:10px;
position: relative;
}
.img {
height: 50px;
}
.placeholder {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #cc2323;
text-align: center;
line-height: 50px;
font-size: 10px;
}
8.通过在模板中使用v-bind指令将组件中的im 属性绑定到imgs数组中的对应图片地址
上,使得每个图片组件都可以显示不同的图片。
v-for="img in imgs" :im="img"
在模板中使用v-bind指令将组件中的show 属性绑定到图片和占位符的显示状态上,实
现了点击图片后显示占位符,再次点击则显示图片的效果。
<img
:src="im"
:style="{ display: show ? 'block' : 'none' }"
class="img"
/>
以下是运行结果
![](https://img-blog.csdnimg.cn/img_convert/d3af7828b3465472545839e5cdcbe9c9.png)