使用el-col和el-row布局,有版心,一页有两栏布局 三栏布局 四栏布局 使用vue动态渲染元素

发布于:2024-07-03 ⋅ 阅读:(16) ⋅ 点赞:(0)

使用Vue结合Element UI的el-rowel-col组件来实现版心布局,并动态渲染不同栏数的布局,可以通过以下步骤实现:

  1. 定义版心容器:使用el-container来定义整个页面的容器,其中el-headerel-mainel-footer分别定义头部、主要内容和底部。

  2. 动态渲染列:使用v-for指令在el-row中动态渲染el-col组件。

  3. 控制列数:通过Vue的数据属性来控制渲染的列数。

下面是一个示例代码,展示如何实现上述功能:

<template>
  <el-container>
    <el-header>头部</el-header>
    <el-main>
      <div class="layout-selector">
        <button @click="setLayout(2)">两栏布局</button>
        <button @click="setLayout(3)">三栏布局</button>
        <button @click="setLayout(4)">四栏布局</button>
      </div>
      <el-row :gutter="20">
        <el-col v-for="(item, index) in cols" :key="index" :span="24 / currentLayout">
          <div>栏目内容 {{ index + 1 }}</div>
        </el-col>
      </el-row>
    </el-main>
    <el-footer>底部</el-footer>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      currentLayout: 2, // 默认两栏布局
      cols: [1, 2, 3, 4], // 栏目数据
    };
  },
  methods: {
    setLayout(layout) {
      this.currentLayout = layout;
    }
  }
};
</script>

<style>
.layout-selector {
  margin-bottom: 20px;
}
</style>

在这个示例中:

  • 使用el-container包裹整个页面,定义了头部、主要内容和底部。
  • el-row中的gutter属性定义了列之间的间距。
  • 使用v-for指令在el-row中动态渲染el-col组件,每个el-colspan属性通过24 / currentLayout计算得出,确保列宽平均分配。
  • setLayout方法用于更改currentLayout的值,从而改变布局的列数。
  • 通过按钮点击事件来动态切换布局的列数。

这样,你就可以根据用户的操作动态地改变页面的布局列数。