Reputation: 19
I want to parse data to show product by using slug from laravel show route resource (get) to vue js components by using laravel api
example: https://shop.app/product/slug-name
i want to parse the slug-name into the vue components
export default {
name: 'product',
mounted() {
// console.log('Component mounted.')
this.fetchData()
},
data(){
return{
products: [],
product: {
id: '',
name: '',
slug: '',
description: '',
image: '',
created_at: '',
updated_at: ''
}
}
},
methods: {
fetchData(){
axios.get('/api/products')
.then((res) => {
this.products = res.data
})
.catch((err) => {
console.log(err)
})
}
}
}
i expect the output from showing the slug name, not show all the products
Upvotes: 1
Views: 2057
Reputation: 26
If you are using Laravel Routes you can get your slug in to your Vue instance like
var slugName = '{{ $slug }}';
export default {
name: 'product',
methods: {
fetchData(){
//you can use slugNname here
axios.get('/api/products/' + slugName)
.then((res) => {
this.products = res.data
})
.catch((err) => {
console.log(err)
})
}
}
after that you can use slugName in your axios request
hope it helps
Upvotes: 0
Reputation: 1373
You can get you current url by
let currentUrl = window.location.pathname;
and then you can use lodash library its already included in laravel if you see you boostrap.js
file
let ar = _.split(currentUrl, '/');
it will return your array. its just like explode
in php. you can read about this here
and at last, get your product by
this.productName = _.last(ar);
`_.last` Its will just give you last element of your array which is your product. [here][2] is the documentation
you can make a method for this. like below
getProductSlug(){
let currentUrl = window.location.pathname;
let ar = _.split(currentUrl, '/');
return _.last(ar);
},
Upvotes: 1