Léon  Peltier

Léon Peltier

1659121200

Choisir Entre Différents Modèles De Code Réutilisables Dans Vue.js ?

En tant que développeurs chez Theodo , nous cherchons toujours des moyens efficaces de réutiliser notre code sans nous répéter (principe DRY). Dans le cadre d'un projet e-commerce utilisant le framework Vue Storefront et Vue 2, nous avons eu l'opportunité d'étudier les meilleures façons de réutiliser les comportements fonctionnels dans Vue.

Nous avons trouvé de nombreuses solutions dans la documentation de Vue telles que Mixins, l'API de composition et les slots scoped. J'espère que cet article vous aidera à choisir le vôtre en fonction de vos projets.

Voici les questions clés auxquelles je répondrai par la suite :

  • Quelle est la meilleure méthode pour partager la logique entre le code dans Vue 2 ?
  • Quels sont les avantages et les inconvénients de l'utilisation de l'API de composition nouvellement développée, des emplacements de portée ou des Mixins pour réutiliser une certaine logique ?
  • Quand faut-il utiliser l'un plutôt que l'autre ?

TL ; RD :

  • L'utilisation de Mixins est l'un des moyens de gérer la logique partageable dans Vue. Mais ils présentent de nombreux inconvénients et doivent être évités dans Vue 2 et Vue 3.
  • Les machines à sous à portée sont une excellente alternative aux Mixins pour Vue 2 et elles ont toujours leur place dans Vue 3.
  • L'API de composition de Vue 3 est un outil puissant pour créer une logique partageable de composants lisibles. C'est l'option que je recommanderais d'utiliser dans la plupart des cas, mais elle est pour l'instant limitée à Vue 3.

Le contexte

Nous avons eu la responsabilité de développer différentes connexions d'authentification pour une plateforme web (Google & Facebook OAuth en plus d'une authentification basique email/mot de passe).

En bref, nous devions créer trois boutons qui déclenchent trois actions différentes. Nos boutons se ressemblaient beaucoup, nous voulions donc éviter de dupliquer le code de l'interface utilisateur. Nous avons donc créé un simple LoginButton.vueprenant 2 props : labelet icon. Le bouton déclenche un événement lorsqu'il est cliqué (événement nommé click).

// components/LoginButton.vue

<template>
  <button @click="$emit('click')">
    <img v-if="icon" :src="icon.src" alt=""/>
    <span>{{ label }}</span>
  </button>
</template>

<script>
export default {
  props: {
    icon: {
      type: Object,
    },
    label: {
      type: String,
      required: true
    }
  }
}
</script>

Notre objectif était de :

  • construire les trois processus d'authentification à l'aide de ce bouton de connexion générique.
  • organiser nos trois logiques de connexion différentes de manière à pouvoir les utiliser n'importe où dans l'application sans nous répéter.
  • garder le code aussi lisible que possible

Avant même de commencer, nous nous sommes demandé si la création de fonctions js de base pour chaque méthode de connexion dans un fichier JS séparé suffirait. Le problème est que la mise en œuvre d'une connexion oauth nécessite l'accès aux hooks du cycle de vie des composants (l'initialisation du client oauth doit être déclenchée dans le hook monté). Cet accès aux options des composants est ainsi devenu une nouvelle exigence dans notre quête de la meilleure solution.

Première piste : définir les différentes méthodes de connexion au sein d'un composant d'emballage

C'était notre première idée. Nous avons créé un composant de page de connexion ( LoginPage.vue) qui utilise notre bouton de connexion et définit trois méthodes à l'intérieur : googleLogin, facebookLogin, et emailLogin. Ces méthodes sont appelées lorsqu'un bouton déclenche son clickévénement.

<!-- LoginPage.vue -->

<template>
    <div class="login-page">
        <button-login label="Login with Google" :icon="googleIcon" @click="loginWithGoogle"/>
        <button-login label="Login with Facebook" :icon="facebookIcon" @click="loginWithFacebook"/>
        <button-login label="Login with email" :icon="emailIcon" @click="loginWithEmail"/>
    </div>
</template>

<script>
import ButtonLogin from './components/ButtonLogin.vue'

export default {
  name: 'LoginPage',
  components: {
    ButtonLogin
  },
  data () {
    return {
      googleIcon: {src: 'path/to/google-icon.png'},
      facebookIcon: {src: 'path/to/facebook-icon.png'},
      emailIcon: {src: 'path/to/email-icon.png'},
    }
  },
  methods: {
    loginWithGoogle () { /* google login logic */ },
    loginWithFacebook () { /* facebook login logic */ },
    loginWithEmail () { /* facebook login logic */ }
  }
}
</script>

Cette solution présentait néanmoins de nombreux inconvénients car nos trois logiques de connexion sont contenues dans un seul composant. Par conséquent:

  • le LoginPagecomposant est grand et peu clair
  • chaque méthode de connexion n'est pas réutilisable dans d'autres parties de la plateforme

En regardant les docs de vue, nous avons entendu parler de Mixins. À première vue, nous pensions que c'était une excellente solution pour la réutilisation de nos logiques de connexion.

Deuxième piste : définir chaque logique de connexion dans un Mixin différent

Un Mixin est un objet contenant des options de composant (données, calcul, méthodes...) qui peuvent être "fusionnées" avec un composant Vue. Au cours de ce processus, les options Mixin sont mélangées avec les options du composant.

A quoi ressemble un Mixin ?

Dans notre cas, voici le squelette GoogleLogin Mixin :

// mixins/GoogleLogin.js

export const GoogleLogin = {
  name: 'GoogleLogin',
  mounted () {
    /* init gapi client */
  },
  methods: {
    loginWithGoogle () {
      /* logic to open google popup, retrieve the authorization code and send it to backend */
    },
    onFailure () {
      /* logic when the sign in method fails */
    },
    onSuccess () {
      /* Logic sending the authorization code to my backend */
    }
  }
}

et notre page de connexion :

// LoginPage.vue

<template>
  <div class="login-page">
    <button-login label="Login with Google" :icon="googleIcon" @click="loginWithGoogle"/>
    <button-login label="Login with Facebook" :icon="facebookIcon" @click="loginWithFacebook"/>
    <button-login label="Login with email" :icon="emailIcon" @click="loginWithEmail"/>
  </div>
</template>

<script>
import ButtonLogin from './components/ButtonLogin.vue'
import { GoogleLogin } from './mixins/GoogleLogin.ts'
import { FacebookLogin } from './mixins/FacebookLogin.ts'
import { EmailLogin } from './mixins/EmailLogin.ts'
export default {
  name: 'App',
  components: {
    ButtonLogin
  },
  mixins: [GoogleLogin, FacebookLogin, EmailLogin],
  data () {
    return {
      googleIcon: { src: 'path/to/google-icon.png', alt: 'google icon' },
      facebookIcon: { src: 'path/to/facebook-icon.png', alt: 'facebook icon' },
      emailIcon: { src: 'path/to/email-icon.png', alt: 'email icon' },
    }
  },
}
</script>

Les mixins semblaient être un moyen efficace d'encapsuler et de partager les différentes logiques de connexion via notre application. Néanmoins, après quelques tests, nous avons rencontré des comportements étranges lors de l'utilisation de Mixins :

  • dépendances implicites : les méthodes et les données de Mixin ne sont pas définies dans le composant LoginPage. En tant que tel, il est déroutant d'utiliser des méthodes ou des données "hypothétiques" (et de ne pas savoir où chaque méthode ou donnée est définie).
  • collision de noms : lors de la fusion des Mixins à l'intérieur du composant de page, certaines de nos méthodes n'étaient pas appelées. Elles ont été remplacées par des méthodes portant le même nom mais définies dans un autre Mixin. Par exemple, si les Mixins FacebookLogin et GoogleLogin ont une onFailureméthode, seule celle définie dans FacebookLogin sera appelée. En effet, le FacebookLogin Mixin est importé après le GoogleLogin Mixin. De plus, si une onFailureméthode est également définie dans le PageLogincomposant, l'appel this.onFailuredéclenchera la méthode onFailure définie dans PageLogin. Par conséquent, aucune des méthodes GoogleLogin et FacebookLogin onFailure ne sera appelée (et cela se produira sans avertissement ni erreur dans la console).

Nous avons ajouté à la liste de nos critères la prévention des dépendances implicites et des collisions de noms.

Sachant cela, nous étions déterminés à ne pas utiliser Mixins. Nous avons décidé de trouver une façon plus propre d'atteindre nos objectifs. C'est à ce moment-là que nous avons entendu parler de la nouvelle API de composition de Vue 3.

Troisième piste : Utiliser l'API de composition de Vue 3

Le 18 septembre 2020, Vue 3 est officiellement sorti avec une nouvelle fonctionnalité géniale pour la réutilisation : l'API de composition . Nous n'entrerons pas dans les détails du fonctionnement de l'API de composition, mais en quelques mots, cette API s'inspire de React Hooks*. Il permet d'encapsuler la logique des composants dans de petits fragments de code réutilisables dans différents composants.

* Il a néanmoins une différence majeure : les hooks de l'API de composition sont appelés une seule fois et utilisent le système de réactivité de Vue tandis que les hooks de réaction peuvent être déclenchés plusieurs fois lors du rendu

Par exemple, nous pourrions écrire ce fragment de code pour la logique d'authentification Google :

// src/composables/useGoogleAuthentication.js

import { onMounted } from 'vue'

export default function useGoogleAuthentication() {
  const initGapiClient = async () => {
    /* initialization of google api client */
  }
  const loginWithGoogle = async () => {
    /* logic to open google popup, retrieve the authorization code and send it to backend */
  }

  onMounted(initGapiClient)

  return {
    loginWithGoogle
  }
}

Ensuite, pour récupérer les informations requises sur notre page de connexion, les useGoogleAuthenticationoptions peuvent être fusionnées dans nos options de page (notamment les données, les méthodes et les données calculées mais aussi les crochets de cycle de vie). Cette fusion est gérée avec l' option du setupcomposant LoginPage.

// LoginPage.vue
<template>
  <div class="login-page">
    <button-login label="Login with Google" :icon="googleIcon" @click="loginWithGoogle"/>
  </div>
</template>

<script>
import ButtonLogin from './components/ButtonLogin.vue'
import useGoogleAuthentication from './composables/useGoogleAuthentication'


export default {
  name: 'App',
  components: {
    ButtonLogin
  },
  data () {
    return {
      googleIcon: { src: 'path/to/google-icon.png', alt: 'google icon' },
    }
  },
  setup() {
    const {loginWithGoogle} = useGoogleAuthentication();
    return {loginWithGoogle};
  },
}
</script>

* Afin d'éviter que la méthode loginWithGoogle ne se déclenche deux fois, vous devrez supprimer l'événement de clic personnalisé dans LoginButton.vue( @click="$emit('click')n'est plus nécessaire dans Vue 3, l'élément racine d'un composant héritera de l'attribut)

Comme vous pouvez le voir, cette solution empêche toute dépendance implicite ou collision de noms car vous devez maintenant importer clairement la partie réutilisable de votre code. La réutilisation de la logique d'authentification dans différentes parties de l'application est simple.

Cette solution semble répondre à nos besoins, non ?

Malheureusement, nous travaillions avec un framework qui ne supportait pas encore Vue 3. Nous avons dû trouver une solution de contournement.

Bon à savoir : Comme prévu dans la roadmap de vue 3 , et surtout parce que le support d'IE risque d'être stoppé pour Vue 3, certaines fonctionnalités compatibles avec le backport seront ajoutées à Vue 2.7. Parmi lesquelles l'API Composition ( le plugin composition api sera fusionné avec Vue 2 Core). Cette modification peut permettre aux utilisateurs de Vue 2 de bénéficier des fonctionnalités de l'API de composition.

Solution : utilisez des emplacements délimités

En regardant un peu plus loin dans la documentation de Vue 2, nous avons trouvé l' attribut v-slot (anciennement nommé slot-scope). Cet attribut nous permet de récupérer des données ou des méthodes d'un composant enfant et de les transmettre aux enfants du composant. Ainsi, pour chaque méthode de connexion, nous avons créé un composant incluant la logique générique de connexion et mettant la méthode de connexion à disposition de ses enfants.

Voici un exemple avec le composant GoogleAuth. Il encapsule la logique de connexion Google et transmet la méthode loginWithGoogle à ses enfants.

// components/GoogleAuth.vue

<template>
  <div>
    <slot :loginWithGoogle="loginWithGoogle" />
  </div>
</template>

<script>
export default {
  data () {
    return {
      auth_code: ''
    }
  },
  mounted () {
    /* init gapi client */
  },
  methods: {
    loginWithGoogle () {
      /* logic to open google popup, retrieve the authorization code and send it to backend */
    },
    onFailure () {
      this.$emit('auth_error', { error: 'google error' });
    },
    onSuccess () {
      this.$emit('auth_success');
    },
  }
}
</script>

Ensuite, le composant GoogleAuth enveloppera un bouton de connexion et lui transmettra la méthode de connexion. (Deux autres composants d'emballage similaires pour Facebook ou e-mail doivent être créés)

// LoginPage.vue

<template>
  <div class="login-page">
    <google-auth
      @auth_error="() => {/* manage authentication errors */}"
      @auth_success="() => {/* manage authentication success (e.g., navigate to another page) */}">
      <template v-slot="{loginWithGoogle}">
        <button-login label="Login with Google" :icon="googleIcon" @click="loginWithGoogle"/>
      </template>
    </google-auth>
  </div>
</template>

<script>
import ButtonLogin from './components/ButtonLogin.vue'
import GoogleAuth from './components/GoogleAuth.vue'
export default {
  name: 'App',
  components: {
    ButtonLogin,
    GoogleAuth
  },
  data () {
    return {
      googleIcon: { src: 'path/to/google-icon.png', alt: 'google icon' },
    }
  },
}
</script>

Cette solution a répondu à nos besoins car elle :

  • encapsule les logiques de connexion dans des composants réutilisables
  • partage la responsabilité du composant UX (bouton) et du comportement fonctionnel (logique de connexion)
  • ne crée pas d'effets secondaires incontrôlés (chaque méthode de connexion est portée au niveau du bouton et non de la page)

Conclusion

Tous les exemples présentés ci-dessus nous permettent de comparer différentes options pour écrire et partager la logique des composants dans Vue JS. Dans votre projet, vous pouvez choisir une option différente selon les critères suivants :

CritèreFonctions JavaScriptMélangesEmplacements délimitésAPI de composition
Encapsuler et réutiliser la logique
Accès aux options de composants telles que les crochets de cycle de vie
Aucune dépendance implicite ou magique
Aucune collision de données
Lisibilité✅ petit composant
❌ gros composant
Où peut-on utiliser la logique partagée ?modèle et
composant
modèle et
composant
modèlemodèle et
composant
Disponible dans Vue 2
Disponible dans Vue 3

En un mot, pour les projets moyens ou grands dans Vue3, je recommanderais fortement d'utiliser l' API de composition car elle permet d'écrire une logique de composant lisible et réutilisable n'importe où dans le code (y compris en dehors des composants). Pour Vue 2, utilisez des slots délimités (pour l'instant) car c'est un moyen assez simple de partager la logique des composants dans Vue 2 sans les inconvénients des mixins. C'est même la meilleure option pour la réutilisation du code lorsqu'il s'agit d'un composant réutilisable qui fournit une interface utilisateur personnalisable dans Vue 2 et Vue 3.

Source : https://blog.theodo.com/2021/06/choose-your-vue-code-reuse-pattern/

#vue 

What is GEEK

Buddha Community

Choisir Entre Différents Modèles De Code Réutilisables Dans Vue.js ?
Monty  Boehm

Monty Boehm

1675304280

How to Use Hotwire Rails

Introduction

We are back with another exciting and much-talked-about Rails tutorial on how to use Hotwire with the Rails application. This Hotwire Rails tutorial is an alternate method for building modern web applications that consume a pinch of JavaScript.

Rails 7 Hotwire is the default front-end framework shipped with Rails 7 after it was launched. It is used to represent HTML over the wire in the Rails application. Previously, we used to add a hotwire-rails gem in our gem file and then run rails hotwire: install. However, with the introduction of Rails 7, the gem got deprecated. Now, we use turbo-rails and stimulus rails directly, which work as Hotwire’s SPA-like page accelerator and Hotwire’s modest JavaScript framework.

What is Hotwire?

Hotwire is a package of different frameworks that help to build applications. It simplifies the developer’s work for writing web pages without the need to write JavaScript, and instead sending HTML code over the wire.

Introduction to The Hotwire Framework:

1. Turbo:

It uses simplified techniques to build web applications while decreasing the usage of JavaScript in the application. Turbo offers numerous handling methods for the HTML data sent over the wire and displaying the application’s data without actually loading the entire page. It helps to maintain the simplicity of web applications without destroying the single-page application experience by using the below techniques:

Turbo Frames: Turbo Frames help to load the different sections of our markup without any dependency as it divides the page into different contexts separately called frames and updates these frames individually.
Turbo Drive: Every link doesn’t have to make the entire page reload when clicked. Only the HTML contained within the tag will be displayed.
Turbo Streams: To add real-time features to the application, this technique is used. It helps to bring real-time data to the application using CRUD actions.

2. Stimulus

It represents the JavaScript framework, which is required when JS is a requirement in the application. The interaction with the HTML is possible with the help of a stimulus, as the controllers that help those interactions are written by a stimulus.

3. Strada

Not much information is available about Strada as it has not been officially released yet. However, it works with native applications, and by using HTML bridge attributes, interaction is made possible between web applications and native apps.

Simple diagrammatic representation of Hotwire Stack:

Hotwire Stack

Prerequisites For Hotwire Rails Tutorial

As we are implementing the Ruby on Rails Hotwire tutorial, make sure about the following installations before you can get started.

  • Ruby on Rails
  • Hotwire gem
  • PostgreSQL/SQLite (choose any one database)
  • Turbo Rails
  • Stimulus.js

Looking for an enthusiastic team of ROR developers to shape the vision of your web project?
Contact Bacancy today and hire Ruby developers to start building your dream project!

Create a new Rails Project

Find the following commands to create a rails application.

mkdir ~/projects/railshotwire
cd ~/projects/railshotwire
echo "source 'https://rubygems.org'" > Gemfile
echo "gem 'rails', '~> 7.0.0'" >> Gemfile
bundle install  
bundle exec rails new . --force -d=postgresql

Now create some files for the project, up till now no usage of Rails Hotwire can be seen.
Fire the following command in your terminal.

  • For creating a default controller for the application
echo "class HomeController < ApplicationController" > app/controllers/home_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating another controller for the application
echo "class OtherController < ApplicationController" > app/controllers/other_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating routes for the application
echo "Rails.application.routes.draw do" > config/routes.rb
echo '  get "home/index"' >> config/routes.rb
echo '  get "other/index"' >> config/routes.rb
echo '  root to: "home#index"' >> config/routes.rb
echo 'end' >> config/routes.rb
  • For creating a default view for the application
mkdir app/views/home
echo '<h1>This is Rails Hotwire homepage</h1>' > app/views/home/index.html.erb
echo '<div><%= link_to "Enter to other page", other_index_path %></div>' >> app/views/home/index.html.erb
  • For creating another view for the application
mkdir app/views/other
echo '<h1>This is Another page</h1>' > app/views/other/index.html.erb
echo '<div><%= link_to "Enter to home page", root_path %></div>' >> app/views/other/index.html.erb
  • For creating a database and schema.rb file for the application
bin/rails db:create
bin/rails db:migrate
  • For checking the application run bin/rails s and open your browser, your running application will have the below view.

Rails Hotwire Home Page

Additionally, you can clone the code and browse through the project. Here’s the source code of the repository: Rails 7 Hotwire application

Now, let’s see how Hotwire Rails can work its magic with various Turbo techniques.

Hotwire Rails: Turbo Drive

Go to your localhost:3000 on your web browser and right-click on the Inspect and open a Network tab of the DevTools of the browser.

Now click on go to another page link that appears on the home page to redirect from the home page to another page. In our Network tab, we can see that this action of navigation is achieved via XHR. It appears only the part inside HTML is reloaded, here neither the CSS is reloaded nor the JS is reloaded when the navigation action is performed.

Hotwire Rails Turbo Drive

By performing this action we can see that Turbo Drive helps to represent the HTML response without loading the full page and only follows redirect and reindeer HTML responses which helps to make the application faster to access.

Hotwire Rails: Turbo Frame

This technique helps to divide the current page into different sections called frames that can be updated separately independently when new data is added from the server.
Below we discuss the different use cases of Turbo frame like inline edition, sorting, searching, and filtering of data.

Let’s perform some practical actions to see the example of these use cases.

Make changes in the app/controllers/home_controller.rb file

#CODE

class HomeController < ApplicationController
   def turbo_frame_form
   end
   
   def turbo_frame submit
      extracted_anynumber = params[:any][:anynumber]
      render :turbo_frame_form, status: :ok, locals: {anynumber: extracted_anynumber,      comment: 'turbo_frame_submit ok' }
   end
end

Turbo Frame

Add app/views/home/turbo_frame_form.html.erb file to the application and add this content inside the file.

#CODE

<section>

    <%= turbo_frame_tag 'anyframe' do %>
            
      <div>
          <h2>Frame view</h2>
          <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
              <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
              <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
              <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
          <% end %>
      </div>
      <div>
        <h2>Data of the view</h2>
        <pre style="font-size: .7rem;"><%= JSON.pretty_generate(local_assigns) %></pre> 
      </div>
      
    <% end %>

</section>

Add the content inside file

Make some adjustments in routes.rb

#CODE

Rails.application.routes.draw do
  get 'home/index'
  get 'other/index'

  get '/home/turbo_frame_form' => 'home#turbo_frame_form', as: 'turbo_frame_form'
  post '/home/turbo_frame_submit' => 'home#turbo_frame_submit', as: 'turbo_frame_submit'


  root to: "home#index"
end
  • Next step is to change homepage view in app/views/home/index.html.erb

#CODE

<h1>This is Rails Hotwire home page</h1>
<div><%= link_to "Enter to other page", other_index_path %></div>

<%= turbo_frame_tag 'anyframe' do %>        
  <div>
      <h2>Home view</h2>
      <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
          <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
          <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
          <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
      <% end %>
  <div>
<% end %>

Change HomePage

After making all the changes, restart the rails server and refresh the browser, the default view will appear on the browser.

restart the rails serverNow in the field enter any digit, after entering the digit click on submit button, and as the submit button is clicked we can see the Turbo Frame in action in the below screen, we can observe that the frame part changed, the first title and first link didn’t move.

submit button is clicked

Hotwire Rails: Turbo Streams

Turbo Streams deliver page updates over WebSocket, SSE or in response to form submissions by only using HTML and a series of CRUD-like operations, you are free to say that either

  • Update the piece of HTML while responding to all the other actions like the post, put, patch, and delete except the GET action.
  • Transmit a change to all users, without reloading the browser page.

This transmit can be represented by a simple example.

  • Make changes in app/controllers/other_controller.rb file of rails application

#CODE

class OtherController < ApplicationController

  def post_something
    respond_to do |format|
      format.turbo_stream {  }
    end
  end

   end

file of rails application

Add the below line in routes.rb file of the application

#CODE

post '/other/post_something' => 'other#post_something', as: 'post_something'
Add the below line

Superb! Rails will now attempt to locate the app/views/other/post_something.turbo_stream.erb template at any moment the ‘/other/post_something’ endpoint is reached.

For this, we need to add app/views/other/post_something.turbo_stream.erb template in the rails application.

#CODE

<turbo-stream action="append" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>
Add template in the rails application

This states that the response will try to append the template of the turbo frame with ID “messages”.

Now change the index.html.erb file in app/views/other paths with the below content.

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 3rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post any message %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>
change the index.html.erb file
  • After making all the changes, restart the rails server and refresh the browser, and go to the other page.

go to the other page

  • Once the above screen appears, click on the Post any message button

Post any message button

This action shows that after submitting the response, the Turbo Streams help the developer to append the message, without reloading the page.

Another use case we can test is that rather than appending the message, the developer replaces the message. For that, we need to change the content of app/views/other/post_something.turbo_stream.erb template file and change the value of the action attribute from append to replace and check the changes in the browser.

#CODE

<turbo-stream action="replace" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>

change the value of the action attributeWhen we click on Post any message button, the message that appear below that button will get replaced with the message that is mentioned in the app/views/other/post_something.turbo_stream.erb template

click on Post any message button

Stimulus

There are some cases in an application where JS is needed, therefore to cover those scenarios we require Hotwire JS tool. Hotwire has a JS tool because in some scenarios Turbo-* tools are not sufficient. But as we know that Hotwire is used to reduce the usage of JS in an application, Stimulus considers HTML as the single source of truth. Consider the case where we have to give elements on a page some JavaScript attributes, such as data controller, data-action, and data target. For that, a stimulus controller that can access elements and receive events based on those characteristics will be created.

Make a change in app/views/other/index.html.erb template file in rails application

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 2rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post something' %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>

<div style="margin-top: 2rem;">
  <h2>Stimulus</h2>  
  <div data-controller="hello">
    <input data-hello-target="name" type="text">
    <button data-action="click->hello#greet">
      Greet
    </button>
    <span data-hello-target="output">
    </span>
  </div>
</div>

Make A changeMake changes in the hello_controller.js in path app/JavaScript/controllers and add a stimulus controller in the file, which helps to bring the HTML into life.

#CODE

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "name", "output" ]

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}

add a stimulus controller in the fileGo to your browser after making the changes in the code and click on Enter to other page link which will navigate to the localhost:3000/other/index page there you can see the changes implemented by the stimulus controller that is designed to augment your HTML with just enough behavior to make it more responsive.

With just a little bit of work, Turbo and Stimulus together offer a complete answer for applications that are quick and compelling.

Using Rails 7 Hotwire helps to load the pages at a faster speed and allows you to render templates on the server, where you have access to your whole domain model. It is a productive development experience in ROR, without compromising any of the speed or responsiveness associated with SPA.

Conclusion

We hope you were satisfied with our Rails Hotwire tutorial. Write to us at service@bacancy.com for any query that you want to resolve, or if you want us to share a tutorial on your query.

For more such solutions on RoR, check out our Ruby on Rails Tutorials. We will always strive to amaze you and cater to your needs.

Original article source at: https://www.bacancytechnology.com/

#rails #ruby 

Aria Barnes

Aria Barnes

1625232484

Why is Vue JS the most Preferred Choice for Responsive Web Application Development?

For more than two decades, JavaScript has facilitated businesses to develop responsive web applications for their customers. Used both client and server-side, JavaScript enables you to bring dynamics to pages through expanded functionality and real-time modifications.

Did you know!

According to a web development survey 2020, JavaScript is the most used language for the 8th year, with 67.7% of people choosing it. With this came up several javascript frameworks for frontend, backend development, or even testing.

And one such framework is Vue.Js. It is used to build simple projects and can also be advanced to create sophisticated apps using state-of-the-art tools. Beyond that, some other solid reasons give Vuejs a thumbs up for responsive web application development.

Want to know them? Then follow this blog until the end. Through this article, I will describe all the reasons and benefits of Vue js development. So, stay tuned.

Vue.Js - A Brief Introduction

Released in the year 2014 for public use, Vue.Js is an open-source JavaScript framework used to create UIs and single-page applications. It has over 77.4 million likes on Github for creating intuitive web interfaces.

The recent version is Vue.js 2.6, and is the second most preferred framework according to Stack Overflow Developer Survey 2019.

Every Vue.js development company is widely using the framework across the world for responsive web application development. It is centered around the view layer, provides a lot of functionality for the view layer, and builds single-page web applications.

Some most astonishing stats about Vue.Js:

• Vue was ranked #2 in the Front End JavaScript Framework rankings in the State of JS 2019 survey by developers.

• Approximately 427k to 693k sites are built with Vue js, according to Wappalyzer and BuiltWith statistics of June 2020.

• According to the State of JS 2019 survey, 40.5% of JavaScript developers are currently using Vue, while 34.5% have shown keen interest in using it in the future.

• In Stack Overflow's Developer Survey 2020, Vue was ranked the 3rd most popular front-end JavaScript framework.

Why is Vue.Js so popular?

• High-speed run-time performance
• Vue.Js uses a virtual DOM.
• The main focus is on the core library, while the collaborating libraries handle other features such as global state management and routing.
• Vue.JS provides responsive visual components.

Top 7 Reasons to Choose Vue JS for Web Application Development

Vue js development has certain benefits, which will encourage you to use it in your projects. For example, Vue.js is similar to Angular and React in many aspects, and it continues to enjoy increasing popularity compared to other frameworks.

The framework is only 20 kilobytes in size, making it easy for you to download files instantly. Vue.js easily beats other frameworks when it comes to loading times and usage.

Take a look at the compelling advantages of using Vue.Js for web app development.

#1 Simple Integration

Vue.Js is popular because it allows you to integrate Vue.js into other frameworks such as React, enabling you to customize the project as per your needs and requirements.

It helps you build apps with Vue.js from scratch and introduce Vue.js elements into their existing apps. Due to its ease of integration, Vue.js is becoming a popular choice for web development as it can be used with various existing web applications.

You can feel free to include Vue.js CDN and start using it. Most third-party Vue components and libraries are additionally accessible and supported with the Vue.js CDN.

You don't need to set up node and npm to start using Vue.js. This implies that it helps develop new web applications, just like modifying previous applications.

The diversity of components allows you to create different types of web applications and replace existing frameworks. In addition, you can also choose to hire Vue js developers to use the technology to experiment with many other JavaScript applications.

#2 Easy to Understand

One of the main reasons for the growing popularity of Vue.Js is that the framework is straightforward to understand for individuals. This means that you can easily add Vue.Js to your web projects.

Also, Vue.Js has a well-defined architecture for storing your data with life-cycle and custom methods. Vue.Js also provides additional features such as watchers, directives, and computed properties, making it extremely easy to build modern apps and web applications with ease.

Another significant advantage of using the Vue.Js framework is that it makes it easy to build small and large-scale web applications in the shortest amount of time.

#3 Well-defined Ecosystem

The VueJS ecosystem is vibrant and well-defined, allowing Vue.Js development company to switch users to VueJS over other frameworks for web app development.

Without spending hours, you can easily find solutions to your problems. Furthermore, VueJs lets you choose only the building blocks you need.

Although the main focus of Vue is the view layer, with the help of Vue Router, Vue Test Utils, Vuex, and Vue CLI, you can find solutions and recommendations for frequently occurring problems.

The problems fall into these categories, and hence it becomes easy for programmers to get started with coding right away and not waste time figuring out how to use these tools.

The Vue ecosystem is easy to customize and scales between a library and a framework. Compared to other frameworks, its development speed is excellent, and it can also integrate different projects. This is the reason why most website development companies also prefer the Vue.Js ecosystem over others.

#4 Flexibility

Another benefit of going with Vue.Js for web app development needs is flexibility. Vue.Js provides an excellent level of flexibility. And makes it easier for web app development companies to write their templates in HTML, JavaScript, or pure JavaScript using virtual nodes.

Another significant benefit of using Vue.Js is that it makes it easier for developers to work with tools like templating engines, CSS preprocessors, and type checking tools like TypeScript.

#5 Two-Way Communication

Vue.Js is an excellent option for you because it encourages two-way communication. This has become possible with the MVVM architecture to handle HTML blocks. In this way, Vue.Js is very similar to Angular.Js, making it easier to handle HTML blocks as well.

With Vue.Js, two-way data binding is straightforward. This means that any changes made by the developer to the UI are passed to the data, and the changes made to the data are reflected in the UI.

This is also one reason why Vue.Js is also known as reactive because it can react to changes made to the data. This sets it apart from other libraries such as React.Js, which are designed to support only one-way communication.

#6 Detailed Documentation

One essential thing is well-defined documentation that helps you understand the required mechanism and build your application with ease. It shows all the options offered by the framework and related best practice examples.

Vue has excellent docs, and its API references are one of the best in the industry. They are well written, clear, and accessible in dealing with everything you need to know to build a Vue application.

Besides, the documentation at Vue.js is constantly improved and updated. It also includes a simple introductory guide and an excellent overview of the API. Perhaps, this is one of the most detailed documentation available for this type of language.

#7 Large Community Support

Support for the platform is impressive. In 2018, support continued to impress as every question was answered diligently. Over 6,200 problems were solved with an average resolution time of just six hours.

To support the community, there are frequent release cycles of updated information. Furthermore, the community continues to grow and develop with backend support from developers.



Wrapping Up

VueJS is an incredible choice for responsive web app development. Since it is lightweight and user-friendly, it builds a fast and integrated web application. The capabilities and potential of VueJS for web app development are extensive.

While Vuejs is simple to get started with, using it to build scalable web apps requires professionalism. Hence, you can approach a top Vue js development company in India to develop high-performing web apps.

Equipped with all the above features, it doesn't matter whether you want to build a small concept app or a full-fledged web app; Vue.Js is the most performant you can rely on.

Original source

 

#vue js development company #vue js development company in india #vue js development company india #vue js development services #vue js development #vue js development companies

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

sophia tondon

sophia tondon

1618971133

Top 10 VueJS Development Companies To Know In 2021-22

Vue.js is one of the most used and popular frontend development, or you can say client-side development framework. It is mainly used to develop single-page applications for both web and mobile. Famous companies like GitLab, NASA, Monito, Adobe, Accenture are currently using VueJS.

Do You Know?

Around 3079 companies reportedly use Vue.js in their tech stacks.
At GitHub, VueJS got 180.9K GitHub stars, including 28.5K GitHub forks.
Observing the increasing usage of VueJS and its robust features, various industry verticals are preferring to develop the website and mobile app Frontend using VueJS, and due to this reason, businesses are focusing on hiring VueJS developers from the top Vue.js development companies.

But the major concern of the enterprises is how to find the top companies to avail leading VueJS development service? Let’s move further and know what can help you find the best VueJS companies.

Read More - https://www.valuecoders.com/blog/technology-and-apps/top-10-vuejs-development-companies/

#hire vue js developer #hire vue.js developers #hire vue.js developer, #hire vue.js developers, #vue js development company #vue.js development company

Luna  Mosciski

Luna Mosciski

1600583123

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.

Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.

Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.

Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.

“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You

#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js