首頁 > web前端 > js教程 > 主體

使用遞歸元件在 Vue 中產生動態佈局

Susan Sarandon
發布: 2024-10-05 06:20:02
原創
126 人瀏覽過

本文的靈感來自於我最近在基於 Vue 的前端上建立動態佈局的實作。

假設您的 API 端點傳回如下所示的 YAML 版面。


---
row:
  - col: 12
    row:
      - col: 12
        component_id: 1
  - col: 12
    row:
      - col: 6
        component_id: 2
      - col: 6
        row:
          - col: 12
            component_id: 3
          - col: 12
            component_id: 4


登入後複製

我們期望此 YAML 表達式具有如下所示的佈局。

Generating dynamic layouts in Vue using recursive components

因此,這使得工作變得很容易,我們將解析這個 YAML 結構並產生 JSON 物件。我使用了 yaml 套件。


npm install yaml



登入後複製

然後,我們可以匯入它並執行解析器。


import YAML from 'yaml'
const jsonObject = YAML.parse(yaml_struct)


登入後複製

為了實現這一點,我們需要建立一個遞歸 Vue 範本和一個在遇到巢狀行時可以遞歸呼叫自身的元件。這樣,該結構將動態處理深度嵌套的佈局,就像我提供的那樣。


<template>
    <v-row>
        <template v-for="col in row">
            <v-col :cols="col.col">
                <template v-if="col.component_id">
                    <ComponentWantToRender :col="col"></ComponentWantToRender>
                </template>

                <template v-if="col.row">
                    <RecursiveRow :row="col.row"></RecursiveRow>
                </template>
            </v-col>
        </template>
    </v-row>
</template>

<script setup>
import { defineProps } from 'vue';
import RecursiveRow from './RecursiveRow.vue';
defineProps({
    row: Array,
});
</script>


登入後複製

現在,我們可以在父元件中使用此 RecursiveRow 元件來處理頂層佈局。


<template>
  <RecursiveRow :row="jsonObject"></RecursiveRow>
</template>

<script setup>
import RecursiveRow from './RecursiveRow.vue';

defineProps({
  jsonObject: Array,
});
</script>


登入後複製

就是這樣。如果您有任何疑問,請在下面留言。

以上是使用遞歸元件在 Vue 中產生動態佈局的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!