【发布时间】:2018-11-04 08:11:15
【问题描述】:
我有一个静态本地 JSON 文件,其中包含我的内容。我正在使用VueResources 和VueRouter。我的目标是制作一个列表组件,用于在本地 JSON 文件中显示项目。然后,如果用户单击某个项目,则在另一个页面中显示该项目的内容。为此,我使用了$route.params。
这是我的列表组件。我称它为 Objects.vue
<template>
<div id="objects">
<router-link :to="'/' + this.lists.id"><div v-for="(item, index) in lists" class="list">{{ item.title }} {{ item.id }}</div></router-link>
</div>
</template>
<script>
//import json from './../assets/data.json'
export default {
name: 'Objects',
data() {
return {
lists: [],
};
},
methods: {
getObjects() {
this.$http.get('/static/data.json')
.then((response) => {
console.log(response.body);
this.lists = response.body.objects;
})
}
},
mounted() {
this.getObjects();
console.log(this.lists.id);
}
};
</script>
<style scoped>
</style>
这是我的项目组件。我称之为 Object.vue
<template>
<div id="object">
<div>
{{ object.id }}
</div>
<div>
{{ object.title }}
</div>
</div>
</template>
<script>
import json from './../assets/data.json'
export default {
name: 'Object',
data() {
return {
id: this.$route.params.id,
object: {},
};
},
methods: {
getObjects() {
this.$http.get('/static/data.json/' + this.id)
.then((response) => {
console.log(response);
this.object = response.body.objects;
})
}
},
mounted() {
this.getObjects();
}
};
</script>
基本上是我的 json 文件
{
"objects": [
{
"id": 0,
"title": "a"
},
{
"id": 1,
"title": "b"
},
{
"id": 2,
"title": "c"
},
{
"id": 3,
"title": "d"
},
{
"id": 4,
"title": "e"
},
{
"id": 5,
"title": "f"
},
{
"id": 6,
"title": "g"
},
{
"id": 7,
"title": "h"
},
{
"id": 8,
"title": "i"
},
{
"id": 9,
"title": "j"
}
]
}
路由/index.js 文件
import Vue from 'vue';
import Router from 'vue-router';
import Visit from '@/components/Visit';
import Objects from '@/components/Objects';
import Community from '@/components/Community';
import Instagram from '@/components/Instagram';
import Object from '@/components/Object';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'Objects',
component: Objects,
},
{
path: '/Visit',
name: 'Visit',
component: Visit,
},
{
path: '/Community',
name: 'Community',
component: Community,
},
{
path: '/Instagram',
name: 'Instagram',
component: Instagram,
},
{
path: '/:id',
name: 'Object',
component: Object,
},
],
});
列表组件工作正常并显示每个项目。但问题是,当我单击一个项目时,id 会返回undefined。出于这个原因,尝试显示http://localhost:8080/undefined
我该如何处理?我错过了什么?
【问题讨论】:
标签: javascript vue.js vuejs2 vue-router vue-resource