select one object from one json file by id vue

僤鯓⒐⒋嵵緔 提交于 2019-12-22 11:37:50

问题


Sorry I'm new to vue but I have to create SPA application so I started playing with the code and I've been using external API and axios to match dynamic routes in my .vue components for json data like this:

data () {
  return {
    post: null,
    nextPost: null,
    prevPost: null,
    total: 0,
    endpoint: 'https://jsonplaceholder.typicode.com/posts/'
  }
},
methods: {
  totalPosts (posts) {
    this.total = posts
  },
  getPost (id) {
    console.log('currentid' + id)

    axios(this.endpoint + id)
      .then(response => {
        this.post = response.data

      })
      .catch(error => {
        console.log('-----error-------')
        console.log(error)
      })
  },
  getNextPost (id) {
    if(id === this.total) {
      this.nextPost = null
    } else {
      axios(this.endpoint + (id * 1 + 1))
        .then(response => {
          console.log(response.data.id)
          this.nextPost = response.data
        })
        .catch(error => {
          console.log('-----error-------')
          console.log(error)
        })
      }
    },

Now I realised that my application will have to use multiple local json files where each one wil contain a lot of json objects. Application will have to choose file by dynamic route and then to choose object by id in that file. It can not use any server side language too. So I'm currently lost what would be the best approach here.


回答1:


this is more of a Javascript question, rather than a Vue question.

when your goal is to select one object from an array of object, .filter() is your friends.

for e.g. https://jsfiddle.net/jacobgoh101/1nv5cesv/3/

if the id you are targeting is 3

axios.get('https://jsonplaceholder.typicode.com/posts/').then(res=>{
  const data = res.data;
    const sampleId = 3;
  const post = data.filter((obj)=>{
    return obj.id === sampleId;
  }).pop();
  console.log(post);
})


来源:https://stackoverflow.com/questions/49485030/select-one-object-from-one-json-file-by-id-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!