Home > Enterprise >  Display JSON file content in Vue
Display JSON file content in Vue

Time:10-01

I've json file with some data. I've to fetch this data and display them in the component.

In my vuex store in actions I have:

async getTodos (context) {
  const todos = []

  const response = await fetch('../../data/todos.json')
  const responseData = await response.json()

  todos.push(responseData)

  context.commit('getTodos', todos)
}

mutations:

getTodos (state, payload) {
  state.todos = payload
}

and state:

state () {
  return {
    todos: []
  }
}

And now how to get this todos in state and display them when Homepage is mounted?

JSON file example:

[
  {
    "id": "1",
    "title": "1st todo",
    "description": "First task",
    "dueTo": "2021-10-03"
  },
  {
    "id": "2",
    "title": "2nd todo",
    "description": "Second task",
    "dueTo": "2021-10-02"
  }
]

CodePudding user response:

Well you can use mapState in your components

<template>
   <div>
      <div>{{todos}}</div>
   </div>
</template>

export default {
   computed: {
      ...mapState(["todos"])
   }
}

CodePudding user response:

You can make getter for todos:

getAllTodos: (state) => state.todos

Then map getters in template :

import { mapGetters } from 'vuex';
computed: {
  ...mapGetters([ 'getAllTodos' ]),
},

<template>
  <ul>
    <li v-for="(todo, i) in getAllTodos" :key="i">{{todo}}</li>
  </div>
</template>
  • Related