【问题标题】:select one object from one json file by id vue通过 id vue 从一个 json 文件中选择一个对象
【发布时间】:2018-03-26 06:12:28
【问题描述】:

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

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 选择对象。 它也不能使用任何服务器端语言。所以我目前不知道这里最好的方法是什么。

【问题讨论】:

    标签: vue.js vuejs2 vue-router


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多