Universal Vue.js application with Nuxt.js part#3 Create components in Nuxt.js, Reusable components, Nuxt-link

in utopian-io •  6 years ago 

Screenshot_17.png

Repository

https://github.com/nuxt/nuxt.js

What Will I Learn?

  • Create components
  • Reusable components
  • Nuxt Link

Requirements

  • Basic Javascript Es6
  • Basic Vuejs
  • Install Nuxt.js
  • Basic Vuex

Resources

Nuxt.js Website - https://nuxtjs.org/
Nuxt.js Github. - https://github.com/nuxt/nuxt.js
Vuex - https://github.com/vuejs/vuex
Poke API - https://pokeapi.co/

Difficulty

  • Intermediated

Tutorial content

I will continue my series tutorial about nuxt.js, in this tutorial we will learn about components on Nuxt.js, we will learn how communication between components and how to use it. Components are an important part of the current frontend framework. We can find the users while the components of the framework such as AngularJs, ReactJs, and VueJs. We will create reusable components and how to implement it with data from the API.

Create components

We will start creating components in Nuxt.js, I will move our HTML code into a component that is stored in the folder components and create an items.vue file.

Items.vue

<template>
  <section class="container">
    <div style="text-align: center;">
      <app-logo/>
      <h1 class="title">
        millenuxt
      </h1>
      <h2 class="subtitle">
        tutorial
      </h2>
    </div>
    <div class="list-group">
        <a href="#" class="list-group-item list-group-item-action active">
          List data from API
        </a>
        <a v-for="item in pokemons" :key="item.name" href="#" class="list-group-item list-group-item-action">{{item.name}}</a>
    </div>
  </section>
</template>
<script>
  import AppLogo from '~/components/AppLogo.vue'
  import {mapState} from 'vuex'
  export default{
    components: {
      AppLogo
    },
    computed: mapState([
      'pokemons'
      ])
  }
</script>

We move the code in the component index.vue into a new component items.vue which we will use repeatedly, then after we move the template we will use it in index.vue.

Use component

There are things to note when we are going to import or use components. we must have the root element to wrap the components we will import.

Example:

<template>
  <div> // This Root Element
    <items> </items> //This component is imported
  </div>
</template>
<script>
  import Items from '~/components/items.vue'
  export default{
    components: {
      Items
    }
  }
</script>
  • Then we can import the file directory of our components import Items from '~/components/items.vue', adjust the file directory you use ~ to facilitate the file directory
    and give aliases to the files you import Items.

  • After you have imported we can not directly use the component, we need to register it on property components: {} and enter the alias name you use when importing, you can add some components by separating with commas (,).

  • If it has finished importing and register it we can use that component with the same tag with its alias name. Alias: Items Tag : <items> </items>

The Result

Run your Nuxt.js project using Npm run dev and we can see the result like this, I will show an error if the alias we listed incomponents: {} is incorrect.
componentduski.gif

Reusable components

The main purpose of creating a component is that we can reuse, a good component is a component that can be used in any template conditions and adjust to the template. by making components that can be used again, we will reduce the risk of redundant when writing code. Other advantages of the components we use change we only need to make changes in the component than on any page will change.

  • Create Reusable components

When we create reusable components, we need to customize our coding. in the previous tutorial, the structure we created is too static, we will make it more dynamic. We will make changes to index.vue.

Changes in component parts

index.vue
API access : http://pokeapi.salestock.net/api/v2/pokemon
Parameter : pokemon

<template>
  <div>
    <items></items>
  </div>
</template>
<script>
  import Items from '~/components/items.vue'
  export default{
    components: {
      Items
    },
    async fetch({strore}){
      await store.dispatch('load_items', 'pokemon')
    }
  }
</script>
  • If we remember again we use nuxtServerInit () method, this method will be automatically called when our project is run, of course, we do not want it. therefore we must create a more specific function to run.

  • async fetch({strore}): by using {store} we can access the store in our Vuex and we will call a function in the store by using the dispatch () function.

  • dispatch (): This function has 1 mandatory parameter that is the name of the function we will call in Vuex Store and we can add another parameter if needed, in the above code we add parameter 'pokemon'. this parameter will be used as API reference that we will access (http://pokeapi.salestock.net/api/v2/pokemon)

Changes in the Vuex Store

After we make changes in the component, we will make changes to the Vuex store. in the previous tutorial, we use the nuxtServerInit () method to run the function automatically. We no longer use this function because we will create a more specific function that will be called as desired instead of automatically.

index.js
Before

import axios from '~/plugins/axios'
export const state = () => ({
    items : []
});
export const mutations = {
    setPokemons(state, items){
        state.pokemons = items
    }
}
export const actions = {
    async nuxtServerInit ({commit}){
        const {data} = await axios.get(url)
        commit('setPokemons', data.results)
    }
}

After

import axios from '~/plugins/axios'
export const state = () => ({
    items : []
});
export const mutations = {
    setItems(state, items){
        state.items = items
    }
}
export const actions = {
    async load_items ({commit}, url){
        const {data} = await axios.get(url)
        commit('setItems', data.results)
    }
}

We make some changes to the variable and do not use nuxtServerInit () we replace it with load_items()function. in this function we will accept the parameters as API reference that we will access , we define it as url, as we know we have a baseUrl API 'http://pokeapi.salestock.net/api/v2/' .The url will then serve as the referring address.

  • Create a new page

Then we will create a page that will also use items.vue component but we will access different APIs.

location_item.vue
API access : http://pokeapi.salestock.net/api/v2/location
Parameter : location

<template>
  <div>
    <items></items>
  </div>
</template>
<script>
  import Items from '~/components/items.vue'
  export default{
    components: {
      Items
    },
    async fetch({store}){
      await store.dispatch('load_items', 'location')
    }
  }
</script>

There is not much difference on the page index.vue and location_item.vue, the difference is the parameter that we pass to the load_items() function. Parameters that pass is a reference API that will be accessed.
to see the result we can run our project with npm run dev and we will see the result as follows:

reusebleduski.gif
We can see we access different APIs of different pages as well, but with the same <items></items> component.

Nuxt Link

We already have more than one page, the right time to add navigation to our project. We will get the default.vue to customize the navbar we took from bootstrap.

default.vue

<template>
  <div>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <nuxt-link tag="a" class="nav-link" to="/">Home</nuxt-link>
          </li>
          <li class="nav-item">
             <nuxt-link tag="a" class="nav-link" to="/location_item">Location</nuxt-link>
          </li>
        </ul>
        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
      </div>
    </nav>
    <nuxt/> 
  </div>
</template>
<style>
html {
  font-family: "Source Sans Pro", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  font-size: 16px;
  word-spacing: 1px;
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  box-sizing: border-box;
}
</style>

This is a navbar template, which we only need to consider is the use of <nuxt-link> that we combine with <navbar> bootstrap.

  • Use Nuxt-link

Example:
<nuxt-link tag="a" class="nav-link" to="/">Home</nuxt-link>

  • We can use nuxt-link to create dynamic navigation, nuxt-link is automatically generated from vue-router.

  • We can initialize what element we will use with tag =" " and we can add class=" ".

  • for the page that we have access to attribute to = "nameOfRoute".

  • Styling Nuxt link

We can add a style to the current link by utilizing the class automatically added by Nuxt-link when the link is active.

Screenshot_2.png


We can use class = "nuxt-link-exact-active" to style the active link, I will add CSS to show the result:

Example:

.nuxt-link-exact-active{
  color:#41B883 !important;
  font-weight: bold;
}

After we finish we can run our project with npm run dev. if there is no error we will see the result as follows:

stylingnuxtduski.gif

We have finished finishing this tutorial, there are some things we learn reusable components from nuxt-link, in the next tutorial series we will learn page transition and create dynamic page in nuxt. thank you, hope this tutorial can help you.

Curriculum

Learn Nuxt#1 Nuxt structure, Global CSS, Request API
Learn Nuxt#2 Vuex in Nuxt.js, Classic Mode and Modules Mode

Proof of Work Done

https://github.com/milleaduski/learnNuxtjs

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
Universal Vue.js application with Nuxt.js part#3 Create components in Nuxt.js, Reusable components, Nuxt-link
Just WoW!

Thank you! Upvote!