那么我的问题很简单,如何使Ruby on Rails应用程序与Vue.js一起工作?如何使vue.js与rails一起工作?
细节
我第一次看vue-rails
宝石,但添加的Vue到轨资产的管道,我想与其他NPM包时,像browserify。然后我看,browserify-rails
,启用js文件夹app/assets/javascript/
commonjs。此外,我打算为每个铁轨控制器制作一个Vuejs应用程序,并使用vue-resource
和vue-router
访问后端操作(如果这不是一个好方法,请告诉我),所以我将以下行添加到了我的布局
<%= javascript_include_tag params[:controller] %>
这将增加与控制器名的js文件,所以UsersController
将有users.js
文件,该控制器的主要VUE应用。
然后,要试试这个我搭建的一个用户轨资源,并使其呈现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
网址(我正在使用c9.io开发),并且仅渲染了/users/index.html.erb
文件。 ,
- 我可能会以错误的方式使用
vue-resource
我的意思传递给get()
功能的网址:那么,啥子是我的猜测。 - 我可能会缺少一些
vue-resource
配置。 - 也许我只是应该使用
vue-rails
宝石与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
在你的'.then'调用中,你没有指定错误处理程序。你应该添加一个日志记录。此外,使用您的网络浏览器的检查员查看实际的网络请求,看它是否按照您期望的方式形成并发送。 –
值得注意的是,vuejs-rails使用过时的vuejs库。如果您使用的是browserify-rails,那么您将不会使用sprockets/application.js。 所以你应该真的选择加载你的JavaScript依赖关系的一种方法。 – ytbryan
@ytbryan我使用sprocket和application.js文件(从这里加载jQuery和bootstrap)以及browserify rails没有问题。无论如何,也许你正确地使用一种方法来管理js依赖关系,但我不知道你为什么陈述过时的vuejs库。 browserify rails会加载过时的Vue.js版本吗? –