【问题标题】:How to use paths/urls/routes dynamically in vue.js/laravel components如何在 vue.js/laravel 组件中动态使用路径/urls/routes
【发布时间】:2020-01-15 07:24:55
【问题描述】:

我正在尝试基于 vue.js/laravel 编写自己的博客软件,用于学习目的。

背景

我在问自己如何编写路径/url 没有硬编码的 vue.js 组件。在下面的示例中,我有一个后列表组件,它列出了数据库中的所有帖子。 json 数据由 laravel api 路由返回(例如 /api/posts)

在列表中,我使用了一个指向 laravel 视图的链接(例如 /posts/{id}),它显示了带有 {id} 的特定帖子的实际正文。

示例

在 laravel 的 api.php 路由文件中,我可以为特定路由命名并将其与 route('api.posts.index') 一起使用。我猜这够动态了吧?

api.php

Route::get('', 'Api\ApiPostsController@index')->name('api.posts.index');

index.blade.php

<post-listing postsview="{{ route('web.posts.show') }}" postsapi="{{ route('api.posts.index') }}"></post-listing>

PostListing.vue

在我的 vue 组件中,我引用了这些属性 postsview 和 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>

问题

是否有“最佳实践”方式或至少有更好的方法?不知何故,我对这个解决方案不满意,但缺乏经验,我不知道从哪里开始。

谢谢。

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:

    有很多方法可以实现这一点,这是我所知道的几个选项。

    1:使用刀片将路由传递给组件

    <component route="{{ route('route_name') }}"></component>
    

    2:你可以用你定义的所有路由保存一个全局变量。

    您可以使用Route::getRoutes()获取所有路线

    并将其添加到您前端的window

    3:使用库,

    这个库完全符合我的想法。 https://github.com/tightenco/ziggy

    如果找到其他选项,请告诉我,这是大多数 laravel 开发人员的常见问题。

    【讨论】:

    • 感谢您的回复。似乎我的方式并没有完全错误。如果我找到另一种方法,我会更新这个网站。
    • 这对我很有帮助
    猜你喜欢
    • 2018-03-11
    • 1970-01-01
    • 2018-06-11
    • 2018-02-14
    • 2017-05-17
    • 2018-10-07
    • 1970-01-01
    • 2022-08-04
    • 2022-10-02
    相关资源
    最近更新 更多