1.Grid布局是什么
grid布局被称为网格布局,元素被指定分配在网格的某一个或者某一些单元格内;这里不做太多基础知识和属性的介绍,默认你已经了解过此布局格式。
2.Grid布局的简单实验
【1】三行三列,九个元素,默认按row排列
<div style="display: grid; grid-template-columns:repeat(3,33%);grid-template-rows:repeat(3,33%);grid-gap:5px; width: 100%; height: 600px;">
<div style="background-color: #42b983">1</div>
<div style="background-color: #0d5aa7">2</div>
<div style="background-color: #FFB951">3</div>
<div style="background-color: #a463f2">4</div>
<div style="background-color: #A60000">5</div>
<div style="background-color: #81b10c">6</div>
<div style="background-color: #f0e0ff">7</div>
<div style="background-color: #7095d5">8</div>
<div style="background-color: #94B3E4">9</div>
</div>
效果:
【2】修改 – grid-template-rows:repeat(5,25%); 按5行分配,实际占用3行,下部会有空白
效果:
3.Grid布局实现el-row/el-col
【1】el-row/el-col是什么?
el-row/el-col是Vue-element组件提供的一种布局方式,可以让我们在一行中定义不同大小比例的元素,例如:
【2】我的思路:
新增两个组件:
外层组件作为Grid布局的容器,将一行分为12等份;并接受grid-gap属性(元素之间的间隔)的值
内层组件利用grid-column-end属性 + span属性 达到占用对应大小的位置的目的
【3】代码:
// 父组件
<template>
<div class="rowStyle" :style="{'grid-gap': gap}">
<slot></slot>
</div>
</template>
<script>
export default {
name: "selfRow",
props: {
gap: {
type: String,
required: true,
}
}
}
</script>
<style scoped>
.rowStyle {
display: grid;
grid-template-columns:repeat(12, 8.33%);
/*grid-gap:10px;*/
width: 100%;
}
</style>
// 子组件
<template>
<div :style="{'grid-column-end': 'span ' + proportion}">
<slot></slot>
</div>
</template>
<script>
export default {
name: "selfColumn",
props: {
proportion: {
type: String,
required: true
}
},
}
</script>
<style scoped>
</style>
// 调用者
<template>
<div>
<self-row gap="1px">
<self-column proportion="2" style="background-color: #FFB951; height: 30px">1</self-column>
<self-column proportion="6" style="background-color: #94B3E4; height: 30px">2</self-column>
<self-column proportion="4" style="background-color: #A60000; height: 30px">3</self-column>
</self-row>
</div>
</template>
<script>
import selfColumn from "./teamModuleType/selfColumn";
import selfRow from "./teamModuleType/selfRow";
export default {
components: {
selfColumn,
selfRow,
},
data() {
return {}
},
}
</script>
【4】效果
2/6/4:
修改proportion的值为 4/4/4 :
至此,调用这两个组件就可以轻松完成我们对一行数据宽度的分配了
【5】注意
需要注意的是grid-gap属性设置的元素间距是不包含在自动分配的空间里面的;也就是说按比例分配的宽度是按照width100% 而不是 width-gap(n-1);所以如果要让宽度适应,应该在父元素里接收到gap值后减去再分配。