Yer*_*lma 8 javascript ruby ruby-on-rails vue.js
好吧,我的问题很简单,如何让Ruby on Rails应用程序与Vue.js一起使用?
细节
我首先看一下vue-railsgem,但是将Vue添加到rails资产管道中,我想使用其他npm包,比如browserify.然后我期待那个,browserify-rails在js文件夹中启用commonjs app/assets/javascript/.我也正打算让每一个轨道控制器Vuejs的应用程序,并获得与后端的行动vue-resource和vue-router(如果这不是一个好办法,请让我知道),所以我加了下面一行到我的布局
<%= javascript_include_tag params[:controller] %>
Run Code Online (Sandbox Code Playgroud)
这将添加一个带有控制器名称的js文件,因此UsersController将具有该users.js控制器的主vue应用程序的文件.
然后,为了尝试这个,我使用rails搭建了一个Users资源,并使其在每个动作中呈现json格式,就像这样
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
Run Code Online (Sandbox Code Playgroud)
这工作正常.然后在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));
});
}
});
Run Code Online (Sandbox Code Playgroud)
当我在chrome中检查dev控制台时,我看到Vue已添加,但我没有看到任何响应,并且我已经插入了一个用户.顺便说一句,我正在尝试使用https://vuejs-rails-yerkopalma.c9users.io/usersurl(我正在使用c9.io进行开发)并且只/users/index.html.erb渲染文件.所以,我的猜测是:
vue-resource错误的方式使用,我的意思是传递给get()函数的url .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
Run Code Online (Sandbox Code Playgroud)
我设法通过Vue.js使其工作。
首先,我向el传递给Vue构造函数的对象添加了属性,然后开始收到错误消息,指出body未定义元素。显然,body元素始终存在于html文件中,因此尽管这是有关Vue实例何时创建的问题。因此,我只是将所有内容都包裹在一个ready事件上。
$(document).on('ready page:change', function() {
var Vue = require('vue');
Vue.use(require('vue-resource'));
new Vue({
el: 'body',
data: {
users: []
},
ready: function(){
this.$http.get('users.json').then(function(response){
console.log(JSON.stringify(response.data));
this.users = response.data;
}, function(response){
console.log("fail");
console.log(JSON.stringify(response));
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
而且效果很好!
因为我使用的是Turbolinks,所以我也包含了page:changeevent。在我看来,index.html.erb我可以访问Vue实例。因此,这使这种情况有效,并且可以解决这个特定问题,但是现在我在处理.vue组件时遇到了另一个问题,也许我将对此提出另一个问题。
请注意,在我的index.html.erb视图中,我可以访问users.js文件assets/javascript/夹中文件中定义的Vue实例,但不能访问Vue或从views文件夹中加载有browserify的任何js模块