i'm trying to write my own blog software based on vue.js/laravel for learning purposes.
I'm asking myself how i write vue.js components in which the paths/urls are not hard coded. In the following example i have a post-listing component which lists all posts from the database. The json data is returned by a laravel api route (eg /api/posts)
In the listing i use a link to a laravel view (eg /posts/{id}) which shows the actual body of a specific post with {id}.
In laravel's api.php route file i can give a name to a specific route and use it with route('api.posts.index')
. That's dynamic enough i guess?
Route::get('', 'Api\ApiPostsController@index')->name('api.posts.index');
<post-listing postsview="{{ route('web.posts.show') }}" postsapi="{{ route('api.posts.index') }}"></post-listing>
In my vue component i refer to these properties postsview
and postsapi
<template>
<div>
<h2 class="title is-2">Recent posts</h2>
<ul>
<li v-for="post in posts['data']" v-bind:key="post.id">
<a :href="postsview + '/' + post.slug" v-text="post.title"></a>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ["postsapi", "postsview"],
data() {
return {
posts: []
};
},
methods: {
getPosts() {
axios.get(this.postsapi).then(response => (this.posts = response.data));
}
},
mounted() {
this.getPosts();
}
};
</script>
Is there a "best-practice" way or at least a better approach? Somehow i'm not happy with this solution, but lacking experience, i don't know where to begin.
Thanks.
There are many ways to achive this, this are a few options that I know of.
1: Use blade to pass the route to the component
<component route="{{ route('route_name') }}"></component>
2: You can save a global variable with all the routes you have defined.
You can use Route::getRoutes()
to get all the routes
and add it to your window
on your front end
3: Use a library,
This library does exactly what you are looking for I think. https://github.com/tightenco/ziggy
If find other options please let me know, this is a common issue for most laravel developers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.