简体   繁体   English

在 Rails 中手动输入路由时无法转到 SPA 页面路由

[英]Can't goto SPA page route when typing route manually in Rails

So far, I made the following setup:到目前为止,我做了以下设置:

  • Created project in Ruby on Rails 7在 Ruby on Rails 7 中创建项目
  • Created Vue project as a directory inside the app directory of rails在 rails 的app目录中创建 Vue 项目作为目录
  • The Vue project is based on: Vue3, Vue-router and Vuex Vue项目基于:Vue3、Vue-router和Vuex
  • I configured the Vue project on build to output in Rails pubic/spa directory, ie serve the SPA app in the static files我在 Rails pubic/spa目录中将构建时的 Vue 项目配置为 output,即在 static 文件中提供 SPA 应用程序
  • So far so good, when I run Rails and build the Vue project, everything is working as expected到目前为止一切顺利,当我运行 Rails 并构建 Vue 项目时,一切都按预期进行
  • When I click on a link on the Vue page, I'm expectedly going to the desired page当我点击 Vue 页面上的链接时,我预计会转到所需的页面
  • However, if I refresh on a routed page (eg spa/about ) Rails throws Routing Error但是,如果我刷新路由页面(例如spa/about ),Rails 会抛出路由错误
  • In addition, if I try typing the route manually, I get the Routing Error again.此外,如果我尝试手动输入路由,我会再次遇到路由错误。

I'm figuring that I need a way to tell Rails to always redirect to the SPA app every time the route prefix is spa我想我需要一种方法来告诉 Rails 每次路由前缀为spa时始终重定向到 SPA 应用程序

Is there a way to config rails to do that?有没有办法配置 rails 来做到这一点?

something like this (in route.rb )像这样的东西(在route.rb中)

# every URL prefix is with spa, redirect to static file `spa/index.html`
get "spa#*" => "spa#*"
# or maybe like this?
prefix :spa # there's no `prefix` method option obviously

I figured it out with some digging and testing.我通过一些挖掘和测试弄明白了。 Here's how you config Rails:以下是配置 Rails 的方法:

1st Create a controller with a single action 1st 用一个动作创建一个 controller

class SpaController < ApplicationController
    def index
        render file: "#{Rails.root}/public/spa/index.html", layout: false
    end
end

2nd config route.rb with the new contoller带有新控制器的第二个配置route.rb

In route.rb file, add the following lineroute.rb文件中,添加以下行

get 'spa/*path', :to => 'spa#index'

explanation解释

The wild card *path is used to catch any "action" while the spa is served as my prefix as I desired in the beginning.通配符*path用于捕捉任何“动作”,而spa是我一开始所希望的前缀。

So for example:例如:

  • http://localhost:3000/spa/about
  • http://localhost:3000/spa/home

All of these routes will be redirect to the same action index in my SpaController .所有这些路由都将重定向到我的SpaController中的相同操作index In the case of Vue-router, it knows how to handle the routing from there.对于 Vue-router,它知道如何从那里处理路由。

I have not tried the same solution on other SPA frameworks (eg Angular), but I think this solution can work with them as well.我没有在其他 SPA 框架(例如 Angular)上尝试过相同的解决方案,但我认为该解决方案也可以与它们一起使用。

Happy frontend program开心前端程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM