2017-01-16 102 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