使用 Vue 3 框架的单文件组件格式(Single-File Component)编写的,这是Vue.js推荐的代码组织方式。单文件组件通常包括三个主要部分:
:在这个部分中定义了组件的模板,也就是用户界面的结构和布局。这里使用了Vue的模板语法,包括v-for、{{ }}等指令和插值表达式。
:这个部分包含了组件的JavaScript逻辑。在Vue 3中,使用了setup()函数来设置组件的响应式数据和方法。
:这个部分定义了组件的样式,包括CSS规则和样式定义。
废话不多说直接上代码
- <template>
-
- <div class="waterfall-container">
-
- <div
- v-for="(item, index) in itemList"
- :key="index"
- class="waterfall-item"
- >
-
- <img :src="item.imageSrc" alt="">
-
- <h2>{{ item.title }}h2>
-
- <p>{{ item.content }}p>
- div>
- div>
- template>
-
- <script>
- import { ref } from 'vue';
-
- export default {
- setup() {
- // 使用ref函数创建响应式数据,存储项目列表
- const itemList = ref([
- {
- imageSrc: 'https://pic.imgdb.cn/item/65084fd3204c2e34d3a96817.jpg',
- title: '我是标题1',
- content: '我是内容1',
- },
- {
- imageSrc: 'https://pic.imgdb.cn/item/650850d7204c2e34d3a984ca.jpg',
- title: '我是标题2',
- content: '我是内容2',
- },
- {
- imageSrc: 'https://pic.imgdb.cn/item/64eee7e1661c6c8e54a86a07.jpg',
- title: '我是标题3',
- content: '我是内容3',
- },
- {
- imageSrc: 'https://pic.imgdb.cn/item/65085109204c2e34d3a9933c.jpg',
- title: '我是标题4',
- content: '我是内容4',
- },
- {
- imageSrc: 'https://pic.imgdb.cn/item/65084fd3204c2e34d3a96817.jpg',
- title: '我是标题5',
- content: '我是内容5',
- },
- ]);
-
- return {
- itemList, // 在setup函数中返回响应式数据
- };
- },
- };
- script>
-
- <style>
- /* 设置瀑布流容器的样式 */
- .waterfall-container {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); /* 列宽自适应,最小300px,平均分配宽度 */
- gap: 20px; /* 项目之间的间隔 */
- }
-
- /* 设置项目样式,如背景色和阴影 */
- .waterfall-item {
- background-color: #fff;
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
- padding: 20px;
- text-align: center;
- }
-
- /* 设置图片样式,使其适应容器宽度 */
- img {
- max-width: 100%;
- height: auto;
- }
- style>