我的问题很简单,如何让 Ruby on Rails 应用程序与 Vue.js 一起工作?
详情
我先看vue-rails
gem,但是将 Vue 添加到 rails Assets 管道,我想使用其他 npm 包,比如 browserify。然后我看看那个,browserify-rails
在 js 文件夹 app/assets/javascript/
中启用 commonjs。我还计划为每个 Rails Controller 制作一个 Vuejs 应用程序,并使用 vue-resource
访问后端操作和 vue-router
(如果这不是一个好方法,请告诉我),所以我在我的布局中添加了以下行
<%= javascript_include_tag params[:controller] %>
这将添加一个带有 Controller 名称的 js 文件,因此 UsersController
将包含 users.js
文件以及该 Controller 的主要 vue 应用程序。
然后,为了尝试这个,我用 rails 搭建了一个 Users 资源,并让它在每个 Action 中呈现 json 格式,就像这样
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
这很好用。然后在 app/assets/javascript/
文件夹中添加 users.js,内容如下
var Vue = require('vue');
Vue.use(require('vue-resource'));
new Vue({
ready: function(){
this.$http.get('users.json').then(function(response){
console.log(JSON.stringify(response));
});
}
});
当我在 chrome 中检查开发控制台时,我看到 Vue 已添加,但我没有看到任何响应,而且我已经插入了一个用户。顺便说一下,我正在尝试使用 https://vuejs-rails-yerkopalma.c9users.io/users
url(我在 c9.io 中开发)并且只有 /users/index.html.erb
文件被渲染。所以,我的猜测是什么:
- 我可能以错误的方式使用了
vue-resource
,我的意思是传递给get()
函数的 url。 - 我可能缺少一些
vue-resource
配置。 - 也许我应该将
vue-rails
gem 与brwoserify-rails
结合使用,但我不知道如何使用。任何帮助或指南将不胜感激。
这是我的 application.js
文件(也包含在我的布局文件中)
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
最佳答案
对于 Rails 5.1+,它将支持 yarn 和 webpack。
此外,还有 this pull request对于 webpacker,Vue 将得到开箱即用的支持。
要开始使用 Vue on Rails,
- 添加
gem 'webpacker'
到 gemfile 捆绑安装
- 运行
rails webpacker:install && rails webpacker:install:vue
或者使用 Rails 5.1x,执行 rails new app --webpack=vue
您将为 Vue on Rails 5 做好准备
关于javascript - 如何使 rails 与 vue.js 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34531280/