【发布时间】:2018-12-23 03:05:53
【问题描述】:
我有一个带有 Story 模型的基本 CRUD rails 5.2 API。我正在构建一个 Vuejs 前端来使用它。目前,/stories 的索引视图成功地从服务器拉取数据。我还可以通过 Stories/new 的 NewStory.vue 将故事添加到数据库中。我现在正在尝试在 stories/:id 的页面上显示一个故事。 api 服务器当前在 v1/stories/:id 处显示我需要的单个结果。
这是我在 services/Api.js 中的内容:
import axios from 'axios'
export default() => {
return axios.create({
baseURL: `http://localhost:3000/v1`
})
}
在 StoriesService.js 中:
import Api from '@/services/Api'
export default {
fetchStories () {
return Api().get('stories')
},
addStory (params) {
return Api().post('stories', params)
},
getStory (params) {
return Api().get('/stories/1')
}
}
在 ViewStory.vue 中:
<template>
<div class="stories">
<h1>Story</h1>
<div v-if="story" class="table-wrap">
<div>
<router-link v-bind:to="{ name: 'NewStory' }" class="">Add
Story</router-link>
</div>
<p>Title: {{story.attributes.title}}</p>
<p>Overview: {{story.attributes.description}}</p>
</div>
<div v-else>
The story with id:{{params}} does not exist <br><br>
<!-- <router-link v-bind:to="{ name: 'NewStory' }"
class="add_story_link">Add Story</router-link> -->
</div>
</div>
</template>
<script>
import StoriesService from '@/services/StoriesService'
export default {
name: 'story',
data () {
return {
title: '',
description: ''
}
},
mounted () {
this.getStory()
},
methods: {
async getStory (params) {
const response = await StoriesService.getStory(params)
this.story = response.data
console.log(this.story)
}
}
}
</script>
使用硬编码的记录 ID,在“网络”选项卡中,我看到对 api 的请求和正在检索的正确记录。
但是,如果我将 getStory 调用更改为 return Api().get('/stories/', params),我会收到 304 响应并且无法检索数据。
我的问题是如何让 StoriesService.js 返回 localhost:3000/v1/stories/params.id,其中 params.id 是 url 中引用的故事的 id。
【问题讨论】:
-
当你从挂载的 getStory 中调用它时,你不会向它传递任何东西:
this.getStory()那么你从哪里得到 id 呢?因为使用路由器参数await StoriesService.getStory(this.$route.params)和getStory (params) { return Api().get(params); }应该可以假设客户端路由/stories/:id指向您的ViewStory -
我对你的改变很生气,但还是没有运气。在视图脚本中: import StoriesService from '@/services/StoriesService' export default { name: 'story', data () { return { title: '', description: '' } },mounted () { this.getStory( ) }, 方法:{ async getStory (params) { const response = await StoriesService.getStory(this.$route.params) this.story = response.data.data console.log(this.story) } }
-
你的 vue 路由器配置是什么样的?你有这样的路线:
/stories/:id? -
我有这个:{ path: '/stories/:id', name: 'ViewStory', component: ViewStory },
-
查看服务器端日志,我没有看到此时正在发出的请求
标签: vue.js ruby-on-rails-5 axios