[Vuejs]-How to fix 'didn't work redirect by Turbolinks' in Ruby on Rails with Vue.js

0๐Ÿ‘

/vueturbo.js

 if (typeof(Vueturbo) === 'undefined') {
       Vueturbo = {};
    }

    Vueturbo.Dispatcher = function() {
       this.dispatch = function() {
          var elements = $('.sjs');
          var cls, meth;

          $(elements).each(function (index, element) {
             tokens  = $(element).attr('data-cls').split('.');
             meth    = $(element).attr('data-method') || 'fire';
             context = window;

             $(tokens).each(function(tidx, token) {
                context = context[token];
             });

             cls = new (context)();
             cls[meth]();
          });
       };

       this.turbolinks = function() {
          var ref = this;
          document.addEventListener('turbolinks:load', function() {
            ref.dispatch();
          });
       };
    };

insert the tag and dispatcher callings in templates
../views/layouts/public.html.erb

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<script charset="utf-8">(new Vueturbo.Dispatcher()).turbolinks();</script>
...
<%= yield %>
...

insert the tag calling the js that you want
../views/public/new.html.erb

<%= hidden_field_tag nil, 'new', class: 'sjs', 'data-cls': 'Vueturbo.new' %>

/new.js

import Vue from 'vue';
import New from '../new.vue';
import TurbolinksAdapter from 'vue-turbolinks';

Vue.use(TurbolinksAdapter);

Vueturbo.new = function() {
  this.fire = function() {
    const el = document.body.appendChild(document.createElement('new'));
    const new_ = new Vue({
        el,
        render: h => h(New)
    });
  }
}

Leave a comment