Vue / PHP - разобрать строку JSON как таблицу - PullRequest
0 голосов
/ 20 июня 2019

Я пытаюсь проанализировать строку JSON, которую мое приложение Laravel предоставляет моему представлению Vue. Строка JSON может выглядеть следующим образом:

{  
   "1":[ { "row":"Some text here on first column." },
         { "row":"And more text. Second row." },
         { "row":"Text!" }
   ],
   "2":[ { "row":"2nd column text." },
         { "row":"" }
   ],
   "3":[ { "row":"Even more text. But on the third column." }
   ]
}

Что следует отметить здесь:

  1. «1», «2» и «3» относятся к столбцам. Так что в приведенных выше примерах у меня есть 3 столбца.
  2. Каждая «строка» относится к строке в столбце.

Я пытаюсь разобрать строку как таблицу, например: https://jsfiddle.net/59bz2hqs/1/

Вот что у меня сейчас:

<template>
    <div>
      <table>
          <tbody>
              <tr v-for="row in this.content">
                 <td>{{row}}</td>
               </tr>
           </tbody>
      </table>
   <div>
</template>

<script>
    export default {
        data() {
            return {

                content: []
            }
        },
        created() {
            Event.$on("document-was-processed", content => {
                this.content = content;          
            });
        }
    }

</script>

Теперь выше просто распечатывает фактическую строку JSON. Кто-нибудь может мне помочь с тем, как на самом деле разобрать контент?

Редактировать

Думая об этом немного больше. На самом деле я не совсем уверен, может ли мой строковый макет JSON даже поддерживать желаемый вывод.

Может, как-то ниже? Не совсем уверен.

{ "1":[
      { "text":"Some text here on first column."},
      { "text":"2nd column text."},
      { "text":"Even more text. But on the third column"}
   ],
   "2":[
      { "text":"And more text. Second row." },
      { "text":"" },
      { "text":"" }
   ],
   "3":[
      { "text":"Text!"},
      { "text":""},
      { "text":""}
   ]}

Тогда что-то вроде:

<table class="text-left w-full border-collapse m-3">
  <thead>
    <tr class="bg-gray-100">

      <th v-for="(item, idx) in this.content" class="p-1">
        {{idx}}
      </th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(row, rid) in this.content">
      <td v-for="(col, cid) in row">{{ col.text }} </td>
    </tr>
  </tbody>
</table>

1 Ответ

2 голосов
/ 20 июня 2019

Вы должны транспонировать свои данные перед их рендерингом.

Это мой фиктивный код

<script>
export default {
  data() {
    return {
      dataTable: []
    };
  },
  created() {
    // Instead of fetching your content I put it in a local variable
    let content = JSON.parse(`{  
   "1":[ { "row":"Some text here on first column." },
         { "row":"And more text. Second row." },
         { "row":"Text!" }
   ],
   "2":[ { "row":"2nd column text." },
         { "row":"" }
   ],
   "3":[ { "row":"Even more text. But on the third column." }
   ]
    }`);
    // Transform object in array of its values
    let data = Object.values(content);
    let colsLength = data.map(r => r.length);
    let maxNumCols = Math.max.apply(Math, colsLength);
    let colsArraySchema = Array.apply(null, Array(maxNumCols)).map((r, i) => i);
    this.dataTable = colsArraySchema.map((col, i) => data.map(row => row[i]));

    // For debug.
    console.log(content);
    console.log(data);
    console.log(colsLength);
    console.log(maxNumCols);
    console.log(this.dataTable);
  }
};
</script>

Теперь вы можете отобразить переменную dataTable в своем шаблоне.(Позаботьтесь о том, чтобы массив строк мог содержать неопределенные значения)

<template>
  <table border="1">
    <tbody>
      <tr v-for="(row, index) in dataTable" :key="index">
        <td v-for="(cell, index) in row" :key="index">
          <span v-if="cell">{{cell["row"]}}</span>
        </td>
      </tr>
    </tbody>
  </table>
</template>

Вы можете увидеть живую демонстрацию здесь: https://codesandbox.io/s/vue-json-transpose-dt915

Надеюсь, это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...