Parte 2: aprenda a usar Vue Router con su SPA

Aprenda a crear un sitio web de entrega de comidas con Vue.js, Vuex, Vue Router y Firebase.
Esta es la segunda parte de mi serie de cuatro sobre la creación de una aplicación Vue. Aquí hay una lista de todas las partes:
Parte 1: Instalar Vue y construir un SPA usando Vuetify y Vue Router
Parte 2: Usar el enrutador Vue
Parte 3: usar Vuex y acceder a la API
Parte 4: uso de Firebase para la autenticación
Resumen
En la primera parte de esta serie, creamos nuestra aplicación Vue usando la CLI de Vue. Además, agregamos Vuetify a la aplicación. Estoy usando Vuetify para diseñar la aplicación. También aprovecharé los muchos componentes de interfaz de usuario que ofrece.
Después de instalar todo, diseñamos la página de inicio de nuestra aplicación.
Usando Vue Router
El enrutador Vue proporciona la navegación para nuestra aplicación. Al hacer clic en el botón INICIAR SESIÓN , se le redirigirá a la página para iniciar sesión. Cuando haga clic en el botón MENÚ , lo redireccionará a la página que muestra los planes de comidas disponibles.
El router.js
archivo contiene la configuración para el enrutamiento. Abra ese archivo. En ese archivo, verá dos rutas. Uno que muestra el componente Home.vue cuando golpea la ‘/’
ruta. El otro muestra el componente about.vue cuando llega a la ruta 'about'.
Necesitaremos crear rutas para cada página de nuestra aplicación. Nuestra aplicación necesitará las siguientes rutas:
- /
- /menú
- /registrarse
- /unirse
Cuando usamos la CLI de Vue para crear la aplicación, seleccionamos instalar Vue Router. De forma predeterminada, esto creó rutas para '/' que es el inicio y '/ about' para la página de información. En la parte 4 usaremos la página Acerca de para mostrar todas las recetas que el usuario ha pedido.
Necesitamos agregar tres nuevas rutas a la matriz de rutas. Después de agregar estas nuevas rutas, este es router.js
el aspecto de nuestro archivo:
import Vue from 'vue';import Router from 'vue-router';import Home from './views/Home.vue';
Vue.use(Router);
export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', component: () => import('./views/About.vue') }, { path: '/menu', name: 'menu', component: () => import('./views/Menu.vue') }, { path: '/sign-in', name: 'signin', component: () => import('./views/Signin.vue') }, { path: '/join', name: 'join', component: () => import('./views/Join.vue') } ]});
Ver vs componentes
En nuestra primera lección, creamos varios componentes nuevos de Vue. Coloqué estos componentes dentro de la carpeta de componentes. Para estos tres nuevos componentes, no los crearemos dentro de la carpeta de componentes. En su lugar, los colocaremos dentro de la carpeta de vistas. La razón es que todo lo que se golpea con una URL como /menu
pertenece a la carpeta de vistas. Todo lo demás debería estar en la carpeta de componentes.
Crear nuevas vistas
Necesitamos crear nuevas vistas para cada una de las tres nuevas rutas. En la carpeta de vistas, cree los siguientes tres archivos:
- Menu.vue
- Signin.vue
- Join.vue
Dentro de cada uno de los archivos agregue un con un. Dentro del diseño tiene un
etiqueta con el nombre de la página.
Aquí está el Menu.vue
archivo:
Menu Page
export default { name: 'Menu'};
Aquí está el signin.vue
archivo:
Signin Page
export default { name: 'Signin'};
Aquí está el Join.vue
archivo:
Join Page
export default { name: 'Join'};
Hacer clic en los elementos del menú
En nuestro menú tenemos cuatro elementos en los que un usuario puede hacer clic. Son:
- Menú
- Perfil
- Registrarse
- Unirse
Queremos configurar cada uno de estos para que cuando un usuario haga clic en ellos lo lleve a la página correspondiente. Abra el archivo AppNavigation.vue. En la sección busque el para el Menú. Todo lo que necesitamos t o do is ad
d para = "/ menú". Haremos esto para las cuatro entradas, pero asegúrese de especificar la ruta correcta que ined in t
definimos el archivo router.js.
We don’t have a menu option to return to the home page. We can fix this by making the app name redirect to the home page. But the title is not a button, so adding to="/menu"
will not work. Vue Router provides the option to surround a link with
Here is what my AppNavigation looks like now:
{{item.title}}
{{appTitle}}; Menu SIGN IN JOIN
export default { name: 'AppNavigation', data() { return { appTitle: 'Meal Prep', drawer: false, items: [ { title: 'Menu' }, { title: 'Profile' }, { title: 'Sign In' }, { title: 'Join' } ] }; }};
When we do this, we have a slight problem with our app title in the menu. It has changed from being white text to being blue text with an underline. This is the default styling for an anchor tag. We can overcome this by adding the following style:
a { color: white; text-decoration: none;}
Now we are back to where we were. If you click on all the items on the menu, they will redirect you to the appropriate page. We only have a slight problem with the About.vue file. This file displays the contents differently. So that we have consistency, update the About.vue file to be this:
About Page
export default { name: 'About'};
Get the Code
Even though this is a 4-part series, you can get the finished code in my GitHub account. Please help me out and star the repo when you get the code.
Summary
In this part of this series, you have learned:
how Vue Router works
how to load new routes
how to setup menu to load each page
What’s Next
In the next part of this series, we will cover using Firebase for Authentication. Vuex allows you to provide “state” within your application. We will be signing up for access to a recipe API. From that API we will be getting recipes to display to users for our menu page.
If you enjoyed this article please clap for it. If you think somebody else would benefit from this article please share it with them.
If you have any questions or find anything wrong with the code, please leave a comment. If there are other topics you would like for me to write about, please leave a comment.
More Articles
Here are some other articles I have written that you might want to read.
Want a job in Tech? Here is how to use the top online marketplace for job seekers to get that job.
LinkedIn is the world’s largest talent pool with 3 million active job listings. Let me show you how you can tap into…medium.freecodecamp.orgInstantiation Patterns in JavaScript
Instantiation patterns are ways to create something in JavaScript. JavaScript provides four different methods to create…medium.comContributing to Open Source isn’t that hard: my journey to contributing to the Node.js project
As a developer, you should consider contributing to open source software. Many of your potential employers will look…medium.freecodecamp.org
Follow Me On Twitter!