[Vuejs]-How can I use Vue.js with json array – simple example

0👍

If you add it to your data like this…

data: {
    items: Info
}

… then you’d access it as items within your template.

As your data has some nesting the tasks would be available as items.Job.Tasks. Here the . for accessing properties works just like it would in any other JavaScript context. Similarly the square bracket notation is also available should you need it.

So something like v-for="task in items.Job.Tasks" would create a loop over your tasks and a local variable called task would be created for each item. This is just like when you’re using forEach to loop over an array, e.g. items.Job.Tasks.forEach(task => {...}).

To get at the sub-tasks you’d then use v-for="subTask in task.SubTasks".

A complete example:

const Info = {
  "Job": {
    "JobId": "123",
    "Tasks": [{
        "TaskId": "1",
        "TaskName": "Test Task 1",
        "SubTasks": [{
            "SubTaskId": "1",
            "SubTaskName": "Test Sub Task 1"
          },
          {
            "SubTaskId": "2",
            "SubTaskName": "Test Sub Task 2"
          },
          {
            "SubTaskId": "3",
            "SubTaskName": "Test Sub Task 3"
          }
        ]
      },
      {
        "TaskId": "2",
        "TaskName": "Test Task 2",
        "SubTasks": [{
            "SubTaskId": "1",
            "SubTaskName": "Test Sub Task 1"
          },
          {
            "SubTaskId": "2",
            "SubTaskName": "Test Sub Task 2"
          },
          {
            "SubTaskId": "3",
            "SubTaskName": "Test Sub Task 3"
          }
        ]
      },
      {
        "TaskId": "3",
        "TaskName": "Test Task 3",
        "SubTasks": [{
            "SubTaskId": "1",
            "SubTaskName": "Test Sub Task 1"
          },
          {
            "SubTaskId": "2",
            "SubTaskName": "Test Sub Task 2"
          },
          {
            "SubTaskId": "3",
            "SubTaskName": "Test Sub Task 3"
          }
        ]
      }
    ]
  }
}

new Vue({
  el: "#ID1",
  data: {
    items: Info
  }
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<div id="ID1">
  <ul>
    <li v-for="task in items.Job.Tasks">
      {{ task.TaskId }} - {{ task.TaskName }}
      <ul>
        <li v-for="subTask in task.SubTasks">
          {{ subTask.SubTaskId }} - {{ subTask.SubTaskName }}
        </li>
      </ul>
    </li>
  </ul>
</div>

Leave a comment