我正在制作一个包含列表页面和详细信息页面(Item.vue)的应用程序。 从列表中,用户可以使用诸如localhost / item / 12345之类的URL转到详细信息页面。 但我不能用VueJS和Vue-router为我的Laravel应用程序制作逻辑。
Laravel 5.4,
节点6.11,npm 3.10.10,
axios 0.15.3,vue 2.3.4,vue-router 2.6.0
我的代码如下所示
Example.vue(用作列表页面)
<template>
<p class="card-text"><router-link v-bind:to="{ name:'item', params:{ id: item.id }}">
{{ item.title }}</router-link>
</p>
</template>
<script>
export default {
data(){
return{
$item:[]
}
},
mounted(){
var self = this;
axios.get('/item').then(function(response){
return self.item = response.data;
});
}
}
</script>
Item.vue
<template>
<p class="card-text">{{item.title}}</p>
<p class="card-text">{{item.content}}</p>
</template>
<script>
export default {
data(){
return{
$item:[]
}
},
mounted(){
var self = this;
axios.get('/item'+this.$route.params.slug
).then(function(response){
return self.item = response.data;
});
}
}
</script>
routes.js
import VueRouter from 'vue-router';
var routes=[
{
name:'item',
path:'/item/:id',
component:require('./components/Item.vue'),
props: true
}
];
export default new VueRouter({
routes
});
路由/ web.js
Route::resource('item','ItemController');
Route::resource('item/{id}', 'ItemController@show');
ItemController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Items;
class ItemController extends Controller
{
public function index()
{
return Items::all();
}
public function show($id)
{
$item = Items::where('id', '=', $id)->firstOrFail();
return view('item.show', compact('item'));
}
}
app.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import router from './routes.js';
require('./bootstrap');
window.Vue = require('vue');
Vue.use(VueRouter);
Vue.component('example', require('./components/Example.vue'));
const app = new Vue({
router,
el: '#app'
});
列表页面显示警告消息
[Vue warn]: Property or method "item" is not defined on the instance but referenced
during render. Make sure to declare reactive data properties in the data option.
found in
---> <Item> at /var/www/laravel/resources/assets/js/components/Item.vue
<Root>
详情页面的错误消息
Error: Request failed with status code 500
答案 0 :(得分:3)
首先,如果你检查错误:
财产或方法&#34;项目&#34;未定义
并检查数据代码中的item
:
data(){
return{
$item:[]
}
},
您使用$定义项目,但使用不带$
的项目变量在Javascript中,您不需要使用美元符号
定义变量将其更改为item.vue
和example.vue
中的项目:
data(){
return{
item:[]
}
},
其次:
检查axios
代码:
axios.get('/item'+this.$route.params.slug
它表示使用get方法调用路由/itemslug
但是我没有在路由器中看到这样的路线定义,但是如果你把这样的物品放在这样的物品之后:
axios.get('/item/'+this.$route.params.slug
它会将您的获取网址更改为:/item/slug
但你不在控制器中使用slug来返回视图 你可以将你的控制器更改为:
public function show($slug)
{
$item = Items::where('slug', '=', $slug)->firstOrFail();
return view('item.show', compact('item'));
}
或将this.$route.params.slug
更改为this.$route.params.id
在你的控制器
public function show($id)
{
$item = Items::where('id', '=', $id)->firstOrFail();
return view('item.show', compact('item'));
}
当你看到show方法返回集合到item.show视图时,如果你想直接用axios获取数据你应该返回视图而不是你可以这样做
public function show($id)
{
return $item = Items::where('id', '=', $id)->firstOrFail();
}