2017-01-16 101 views
2

让我解释一下我正在工作的例子。我的项目是在laravel 5. *。我提到了firstsecond链接,但没有运气。Vue Js - 如何从网址获取slug?

我有2个文件brand_detail.blade.phpbrand_detail.js

当我打开http://localhost/gift_india/brand/baskin-robbins网址是调用brand_detail.blade.php文件,以便在这个网址巴斯金罗宾斯是我的slu。。所以我想通过baskin-robbins到vue js并且想获得这个品牌项目的数据。

brand_detail.blade.php文件

<div id="container_detail"> 
<brand-detail></brand-detail> 
</div> 

<template id="brand-detail-template"> 

@{{detail}} 

</template> 

brand_detail.js文件

Vue.component('brand-detail', { 

template: '#brand-detail-template', 

data: function(){ 

    return { 

     detail: [] 

    } 

}, 

created: function(){ 
    var slug = this.$route.params.slug; // here I'm getting error that Uncaught TypeError: Cannot read property 'params' of undefined 
    console.log(slug); 



    axios.get('brand_detail/:slug') 
     .then(function (response) { 
      console.log(response.data); 

     }) 
     .catch(function (error) { 
      console.log(error.data); 
     }); 
} 
}); 

new Vue({ 

el: '#container_detail' 

}) 

在我blade_detail.blade.php文件我有以下包含js文件。

<script src="https://unpkg.com/vue/dist/vue.js"></script> 
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> 
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> 

UPDATE

我使用laravel 5.3这样的路线在路线/ web.php文件中定义,我的路线是像下面。

当我点击从品牌列表页中的任何品牌,然后在下面的路线是使用: 为前:我有12个品牌列表页面像巴斯金·罗宾斯,贝纳通,今日咖啡团结的颜色。

现在,如果我点击巴斯金·罗宾斯品牌那么这就是所谓的路线如下:

Route::get('/brand/{slug}', function() { 

return view('brand_detail'); 
}); 

当这brand_deta il叶片模板打开我的网址就像http://localhost/gift_india/brand/baskin-robbins所以从这个URL我想通过baskin-robbins到vue js并且想要调用下一个路由获取所有数据为baskin-robbins品牌。

回答

2

由于您使用的是laravel router,因此您可以使用此变量$slug获取slug。你需要在你的vue实例中得到这个。从这个answer获得灵感,你应该能够做到以下几点:

brand_detail。JS

var slug = '{{ $slug }}'; 

Vue.component('brand-detail', { 

    template: '#brand-detail-template', 
    data: function(){ 
    ... 
    ... 
    //use slug variable 
    ... 
    ... 

如果您正在使用VUE路由器

你所得到的误差this.$route是不确定的,你有没有在VUE实例注入路由器。

请确保在Vue初始化中添加您的路由器对象,请参阅此工作fiddle

const routes = [ 
    { path: '/foo', component: Foo }, 
    { path: '/bar', component: Bar } 
] 

const router = new VueRouter({ 
    routes // short for routes: routes 
}) 

// Create and mount the root instance. 
// Make sure to inject the router with the router option to make the 
// whole app router-aware. 
const app = new Vue({ 
    router, 
    el: '#container_detail' 
}) 
+0

问问题之前,我在这里检查http://jsfiddle.net/yyx990803/xgrjzsup/,但我不知道如何添加代码与我的项目,所以你能不能给我例如我的代码?我的路线将是http:// localhost/gift_india/brand_details /:slug。 – Dhaval

+0

@watson你在哪里定义了路线,你可以添加代码吗? – Saurabh

+0

我已更新我的问题,以便您了解我的路线。 – Dhaval