Cómo usar el enrutamiento en Vue.js para crear una mejor experiencia de usuario

Vue.js es un gran marco de JavaScript creado por Evan You. Se utiliza para crear aplicaciones de página web única y componentes flexibles, y es una de las habilidades más necesarias en el desarrollo web front-end. Puede obtener más información sobre Vue.js aquí.

Vue.js proporciona una serie de funciones que le permiten crear componentes web reutilizables. El enrutamiento es uno de esos métodos. Permite al usuario cambiar entre páginas sin actualizar la página. Esto es lo que hace que la navegación sea fácil y realmente agradable en sus aplicaciones web.

Entonces, en este artículo, explicaré cómo funcionan los enrutadores Vue.js construyendo una plantilla Vue como ejemplo.

Empezando

Entonces, comencemos con nuestro proyecto Vue.js Route r instalando y creando un nuevo proyecto Vue.js. Necesitamos tener Node.js instalado. Usaremos vue-cli para generar un nuevo proyecto de Vue.js. Siga los pasos que se indican a continuación:

Escriba el siguiente código en su terminal y ejecute:

vue init webpack vue-router
//cd vue-router//npm run dev

Vaya a // localhost: 8080

Abra la aplicación en su editor de texto. Dentro de la carpeta de componentes, abra el HellowWorld.vuearchivo y siga estos pasos:

  • Cambiar nombre HellowWorld.vuea home.vue. Elimine todo el código y reemplácelo con esto:

Home

export default { name: 'home', data () { return { msg: 'Welcome to Your Vue.js App' } }}
  • Vaya index.jsdentro de la carpeta del enrutador y reemplácelo HelloWorldcon home:
import Vue from 'vue'import Router from 'vue-router'import home from '@/components/home'
Vue.use(Router)
export default new Router({ routes: [ { path: '/', name: 'home', component: home } ]})

El App.vuearchivo debería verse así:

export default { name: 'App'}
#app { }

¡Y ahora escribamos nuestro código!

Ahora vamos a agregar una plantilla de Bootswatch. Puede elegir cualquier plantilla que desee. Elegiré a Cosmo. Haga clic en Ctrl + U para ver el código fuente y simplemente copie el Navbar(solo necesitamos la barra de navegación). Pegue este código en App.vuecomponente.

Aquí estamos ?

A continuación, vamos a crear otros tres componentes: Blog, Servicesy Contact.

Dentro de la carpeta de componentes, cree un nuevo archivo, asígnele un nombre blog.vuee inserte este código en él:

{{blog}}

export default{ name:'blog', data (){ return{ title:'Blog' } } }

Si desea hacer lo mismo para el componente de servicio y contacto, debe tener estos archivos en la carpeta de su componente:

  • home.vue
  • blog.vue
  • services.vue
  • contact.vue

Configuración de enrutadores

Ahora, después de crear estos cuatro componentes, debemos configurar los enrutadores para que podamos navegar entre los componentes.

Entonces, ¿cómo podemos navegar a cada componente usando los enrutadores?

Necesitamos aprender las reglas de enrutamiento. Ahora, tenemos que hacer algunas modificaciones dentro de la carpeta del enrutador, así que abreindex.js

Sigue estos pasos:

  • Primero importe sus componentes a index.js. Importe todos los componentes utilizando el importmétodo.
import home from '@/components/home'import blog from '@/components/blog'import services from '@/components/services'import contact from '@/components/contact'
  • Segundo módulo de enrutador y Vue de importación del módulo de enrutador vue:
import Vue from 'vue'import Router from 'vue-router'
// use routerVue.use(Router)

Si ha instalado Vue con vue-cli, tendrá el módulo vue-router importado de forma predeterminada.

  • Finalmente, dentro de la carpeta del router, tenemos que configurar los routers para que funcionen. El método del enrutador toma una matriz de objetos que a su vez toma las propiedades de cada componente:
export default new Router({ routes: [ { path: '/', name: 'home', component: home }, { path: '/blog', name: 'blog', component: blog }, { path: '/services', name: 'services', component: services }, { path: '/contact', name: 'contact', component: contact } ]})
  • path : la ruta del componente
  • name: el nombre del componente
  • component : la vista del componente

Para convertir cualquier componente en el componente predeterminado, establezca una barra inclinada ('/') en la propiedad de ruta:

path:'/'

In our example, we set the home page as the default page. Now, when you open the the project in the browser, the first page that will appear is the home page.

{path:'/',name:'home',component:home}

The vue-router has more advanced parameters and methods, but we are not jumping into this section at this point.

This is the list of properties and methods that you can use with vue-router:

  • Nested routers
  • Named view
  • Redirect and Alias
  • Navigation Guard
  • Router instance

Now you can browse to any components by typing the name of the component!

router-link

Now we are going to set up the navigation through the Navbar that we created usingthe router-link element.

To do that, we should replace the </a> element by &lt;/router/link> like this:

  • Blog
  • Services
  • contact
  • The router-link takes the to='path' attribute that takes the path of the component as a value.

    Router-view

    You will find the ew> tag i n the App.vue file. It’s basically the view where the components are rendered. It’s like the main div that contains all the components, and it returns the component that match the current route. We will di scuss route-view in the next part when we use the animation transition .

    Using the parameters inside the routers

    At this point, we will use parameters to navigate to specific components. The parameters make the routing dynamic.

    To work with parameters, we are gonna create a list of products and an array of data. When you click on the link of any product, it will take us to the page details through a parameter.

    In this situation, we are not going to use a database or API to retrieve the products’ data. So what we have to do is create an Array of products that will act as a database.

    Inside the home.vue component, put the Array within the data() method just like this:

    export default { name: 'home', data () { return { title: 'Home', products:[ { productTitle:"ABCN", image : require('../assets/images/product1.png'), productId:1 }, { productTitle:"KARMA", image : require('../assets/images/product2.png'), productId:2 }, { productTitle:"Tino", image : require('../assets/images/product3.png'), productId:3 }, { productTitle:"EFG", image : require('../assets/images/product4.png'), productId:4 }, { productTitle:"MLI", image : require('../assets/images/product5.png'), productId:5 }, { productTitle:"Banans", image : require('../assets/images/product6.png'), productId:6 } ] } }}

    Then fetch and loop into the Products Array using the v-for directive .

    {{data.productTitle}}

    The result:

    To navigate to the details component, we first have to add a click event:

    {{data.productTitle}}

    Then add methods:

    methods:{ goTodetail() { this.$router.push({name:'details'}) }

    If you click the title, it will return undefined because we haven’t created the details component yet. So let’s create one:

    details.vue

    {{title}}

    export default{ name:'details', data(){ return{ title:"details" } } }

    Now we can navigate without getting an error ?

    Now how can we browse to the details page and get the matched data if we don’t have a database?

    We are going to use the same products array in the details component. So we can mach the id that comes from the URL:

    products:[ { productTitle:"ABCN", image : require('../assets/images/product1.png'), productId:1 }, { productTitle:"KARMA", image : require('../assets/images/product2.png'), productId:2 }, { productTitle:"Tino", image : require('../assets/images/product3.png'), productId:3 }, { productTitle:"EFG", image : require('../assets/images/product4.png'), productId:4 }, { productTitle:"MLI", image : require('../assets/images/product5.png'), productId:5 }, { productTitle:"Banans", image : require('../assets/images/product6.png'), productId:6 } ]

    First we have to set the id to the goTodetail() method as a parameter:

    {{data.productTitle}}

    Then add a second parameter to the router method.

    The $router method takes two parameters: first, the name of the component we want to navigate to, and second, the id parameter (or any other parameter).

    this.$router.push({name:'details',params:{Pid:proId}})

    Add Pid as the parameter in index.js inside the router folder:

    { path: '/details/:Pid', name: 'details', component: details }

    home.vue

    methods:{ goTodetail(prodId) { this.$router.push({name:'details',params:{Pid:proId}}) } }

    To get the matched parameter, use this line of code:

    this.$route.params.Pid

    details.vue

    the product id is :{{this.$route.params.Pid}}

    Then loop through the products array indetalils.vue and check the object that matchs the parameter Pid and return its data:

    {{product.productTitle}}

    ///export default{ name:'details', data(){ return{ proId:this.$route.params.Pid, title:"details" }}

    You see now that when we click any product’s link it get us to that product!

    detail.vue component:

    {{product.productTitle}}

    export default{ name:'details', data(){ return{ proId:this.$route.params.Pid, title:"details", products:[ { productTitle:"ABCN", image : require('../assets/images/product1.png'), productId:1 }, { productTitle:"KARMA", image : require('../assets/images/product2.png'), productId:2 }, { productTitle:"Tino", image : require('../assets/images/product3.png'), productId:3 }, { productTitle:"EFG", image : require('../assets/images/product4.png'), productId:4 }, { productTitle:"MLI", image : require('../assets/images/product5.png'), productId:5 }, { productTitle:"Banans", image : require('../assets/images/product6.png'), productId:6 } ] } } }

    The transition

    In this part, we are going to add an animation transition to the animated component. We will animate the transition of the components. It makes the navigation awesome, and it creates a better UX and UI.

    To make an animation transition, put the “” inside the “” tag and give it a name of class.

    App.vue

    To animate the transition of the component when it enters the view, add enter-activeto the name given to the transition tag. Then addleave-activeand then give it the CSS transition properties just like this:

    .moveInUp-enter-active{ opacity: 0; transition: opacity 1s ease-in;}

    Using CSS3 animation

    Now we are gonna animate using @keyframes in CSS3.

    When the component enters the view, add a fade effect to the view.

    .moveInUp-enter-active{ animation: fadeIn 1s ease-in;}@keyframes fadeIn{ 0%{ opacity: 0; } 50%{ opacity: 0.5; } 100%{ opacity: 1; }}

    Add another fade effect when the component leaves the view.

    Now we’re going to make the component move in and up when it leaves the view.

    .moveInUp-leave-active{ animation: moveInUp .3s ease-in;}@keyframes moveInUp{ 0%{ transform: translateY(0); } 100%{ transform: translateY(-400px); }}

    Now you can create you own animations and transitions for your components.

    That’s it — we are done ! ?

    You can Download the Source code here .

    Wrapping up

    Routing in Vue.js makes your app pretty awesome when it come to navigation. It give it that energy of the single page web application, and it creates a better user experience.

    By the way…

    If you want to learn Bootstrap 4, check out my class on Skillshare with this referral link and get 2 free months access to 20,000 classes.

    Originally published on zeolearn.com

    Subscribe to this mailList to learn more about Front End topics, and Follow me on Twitter.

    By the way, I’ve recently worked with a strong group of software engineers for one of my mobile applications. The organization was great, and the product was delivered very quickly, much faster than other firms and freelancers I’ve worked with, and I think I can honestly recommend them for other projects out there. Shoot me an email if you want to get in touch — [email protected].