通过 id vue 从一个 json 文件中选择一个对象 [英] select one object from one json file by id vue

查看:39
本文介绍了通过 id vue 从一个 json 文件中选择一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我是 vue 新手,但我必须创建 SPA 应用程序,所以我开始使用代码,并且我一直在使用外部 API 和 axios 来匹配 .vue 组件中的动态路由以获取 json 数据,如下所示:

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)
        })
      }
    },

现在我意识到我的应用程序将不得不使用多个本地 json 文件,其中每个文件都将包含许多 json 对象.应用程序必须通过动态路由选择文件,然后在该文件中通过 id 选择对象.它也不能使用任何服务器端语言.所以我现在不知道这里最好的方法是什么.

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.

推荐答案

这更像是一个 Javascript 问题,而不是一个 Vue 问题.

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

当您的目标是从一组对象中选择一个对象时,.filter() 是你的朋友.

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

例如https://jsfiddle.net/jacobgoh101/1nv5cesv/3/

如果您定位的 ID 是 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);
})

这篇关于通过 id vue 从一个 json 文件中选择一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆