Vue.js 路由器,在 Rails 条路线上有 Ruby

Vue.js router with Ruby on Rails routes

我目前正在开发一个在 Rails 后端和 Vue.js 前端具有 Ruby 的应用程序。这是一个单页应用程序。我正在使用 webpacker gem 构建我的主要 JS 文件。

我添加了 vue-router 和一些前端路由。我可以使用 <router-link> 进行导航,它可以正确呈现相应的组件。我想不通的是如何设置我的前端路由,以便有人可以直接导航到 URL 而无需点击我的 Rails 路由。

例如,如果我输入 /sample-route,我想点击我的 Vue.js 路线,而不是我的 Rails 路线。我仍然希望能够对我的 Rails 路由进行 API 调用。例如 /api/users.

根据你有多少路由,你可以将你的 Vue 路由添加到 routes.rb 并将它们发送到你的根 Vue 应用程序路由。例如Webpacker 正在使用 controller#action vue_controller#app 呈现您的 js 包。您的 Vue 应用程序路由器使用 /user/profile。在routes.rb中添加一条路线:

get "/user/profile" => "vue_controller#app" # <- The controller action rendering your Vue pack

如果重新定义 routes.rb 中的每个 Vue 路由似乎无法维护,您可能需要研究将它们发送到 vue 应用程序控制器操作的通用回退路由。只要您不更改路由,而只是响应 Vue 控制器操作,Vue 路由器就会在页面加载时负责为该路由呈现正确的组件。

在 Rails 4 中,您可以使用类似于此 SO 问题中答案的内容来帮助您设置 "catch-all" 路由 Rails catch-all route

编辑:使用捕获所有路由确实会导致 404 出现一些问题。如果用户请求不存在的路由,Rails 应用程序仍会向他们发送 Vue 包。要解决此问题,您需要在 Vue 路由器中添加一些未知路由处理以呈现类似 404 页面的内容。

通过将 <router-view></router-vew> 添加到我的主要 Vue.js 组件中,我的问题得到了解决。

这也是我的 rails 路由文件:

Rails.application.routes.draw do
  namespace :api do
    # api routes here
  end

  root 'application#index'
  get '/*path', to: 'application#index' 
end

还有一种方法很有用,也可以处理子路由(在单个 rails 应用程序中每个页面都有单独的 vue 应用程序):

routes.rb

Rails.application.routes.draw do
    # this route entry will take care of forwarding all the page/* urls to the index
    get 'page_controller/*path', to: 'page_controller#index', format: false
end

另外,请根据设计分别处理api和索引路由。

vue-routes.js

const router = new VueRouter({
  mode: 'history',
  base: '/page_url',
  routes: [
    ...
  ]
});