select 来自一个 json 文件的一个对象(按 ID vue)
select one object from one json file by id vue
抱歉,我是 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 选择对象。
它也不能使用任何服务器端语言。所以我目前不知道这里最好的方法是什么。
这更像是一个 Javascript 问题,而不是 Vue 问题。
当你的目标是 select 对象数组中的一个对象时 ,.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);
})
抱歉,我是 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 选择对象。 它也不能使用任何服务器端语言。所以我目前不知道这里最好的方法是什么。
这更像是一个 Javascript 问题,而不是 Vue 问题。
当你的目标是 select 对象数组中的一个对象时 ,.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);
})