Sådan bruges routing i Vue.js til at skabe en bedre brugeroplevelse

Vue.js er en fantastisk JavaScript-ramme oprettet af Evan You. Det bruges til at oprette apps til en enkelt webside og fleksible komponenter, og det er en af ​​de mest krævede færdigheder i Front End Web-udvikling. Du kan lære mere om Vue.js her.

Vue.js indeholder en række funktioner, der giver dig mulighed for at oprette genanvendelige webkomponenter. Routing er en af ​​disse metoder. Det giver brugeren mulighed for at skifte mellem sider uden at opdatere siden. Dette er, hvad der gør navigering let og virkelig rart i dine webapplikationer.

Så i denne artikel forklarer jeg, hvordan Vue.js-routere fungerer ved at oprette en Vue-skabelon som et eksempel.

Kom godt i gang

Så lad os komme i gang med vores Vue.js Route r- projekt ved at installere og oprette et nyt Vue.js-projekt. Vi skal have Node.js installeret. Vi bruger vue-cli til at generere et nyt Vue.js-projekt. Følg nedenstående trin:

Indtast følgende kode i din terminal, og kør:

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

Gå til // localhost: 8080

Åbn appen i din teksteditor. Inde i komponentmappen skal du åbne HellowWorld.vuefilen og følge disse trin:

  • Omdøb HellowWorld.vuetil home.vue. Fjern al koden, og udskift den med denne:

Home

export default { name: 'home', data () { return { msg: 'Welcome to Your Vue.js App' } }}
  • index.jsind i router- mappen og erstat HelloWorldmed 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 } ]})

Den App.vuefil skal se sådan ud:

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

Og lad os nu skrive vores kode!

Vi skal nu tilføje en Bootswatch-skabelon. Du kan vælge en hvilken som helst skabelon, du kan lide. Jeg vælger Cosmo. Klik på Ctrl + U for at få vist kodekilden og bare kopiere den Navbar(vi skal bare bruge navlinjen). Indsæt denne kode i App.vuekomponent.

Her er vi ?

Dernæst vi skal skabe tre andre komponenter: Blog, Servicesog Contact.

Inde i komponentmappen skal du oprette ny fil, navngive den blog.vueog skub denne kode ind i den:

{{blog}}

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

Hvis du vil gøre det samme for service- og kontaktkomponenten, skal du have disse filer i din komponentmappe:

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

Routere konfigureres

Efter at have oprettet disse fire komponenter er vi nødt til at konfigurere routerne, så vi kan navigere mellem komponenterne.

Så hvordan kan vi navigere til hver komponent ved hjælp af routerne?

Vi er nødt til at lære reglerne for ruting. Nu skal vi foretage nogle ændringer inde i routermappen, så åbenindex.js

Følg disse trin:

  • Importér først dine komponenter til index.js. Importer alle komponenter ved hjælp af importmetoden.
import home from '@/components/home'import blog from '@/components/blog'import services from '@/components/services'import contact from '@/components/contact'
  • Anden import af Vue og routermodul fra vue-routermodul:
import Vue from 'vue'import Router from 'vue-router'
// use routerVue.use(Router)

Hvis du har installeret Vue med vue-cli, får du vue-routermodulet importeret som standard.

  • Endelig skal vi inde i routermappen konfigurere routerne til at få dem til at fungere. Routermetoden tager en række objekter, som igen tager hver komponents egenskaber:
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 : stien til komponenten
  • name: navnet på komponenten
  • component : udsigten til komponenten

For at gøre en hvilken som helst komponent til standardkomponenten skal du indstille skråstreg ('/') til stiegenskaben:

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].