Friday, October 19, 2018

Simple blog with Nuxt

Following my enthusiasm about Nuxt.js and Vue.js, here another step.
In this post, I’m going to outline the additional steps to build a bare bones blog using Nuxt.
This is a very basic blog with an index template, a sidebar and a post template using a json array as the data source.
The notable differences from the previous tutorial are essentially two.

Using external data

The index page is a template that will be populated by means of an array of objects that comes from an ajax request, and this is the Nuxt way to do that:
<template>
  <article>
    <h1>Index</h1>
    <div class="grid">
      <ul>
        <li v-for="article in articles" class="item">
          <nuxt-link :to="'/article/' + article.id">{{ article.title }}</nuxt-link>
        </li>
      </ul>
    </div>
  </article>
</template>


<script>
import axios from 'axios'

export default {
  title: 'Hey there',
  async asyncData () {
    const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts')
    return {articles:data}
  }
}

</script>
You can see the template will iterate over the article array to build the titles list.

Dynamic page

So far, every page we want to publish needs to be created as .vue component, manually, in pages folder. In our case, we need to deal with an array of objects where each object should become an article. Nuxt provides a way to setup a .vue component that acts as a master to generate multiple pages out of it.
Inside the pages folder, let’s create another folder named article (or choose your own) and within it put a .vue component named _id.vue with the following source:
<template>
  <article>
    <h1>{{title}}</h1>
    <p>{{body}}</p>
    <nuxt-link :to="'/'">Back</nuxt-link>
  </article>
</template>

<script>
import axios from 'axios'

export default {
  validate ({ params }) {
    return !isNaN(+params.id)
  },
  async asyncData({params, error}){
    const {data} = await axios.get(`https://jsonplaceholder.typicode.com/posts/${+params.id}`)
    return data
  }
}

</script>

Test the shit

Using the usual npm run dev command, you can check in-browser your progress.
To generate the pages we need to run the command npm run generate. Before to run it we need to add the last detail in order to make it work properly. Nuxt needs a way to know which are the dynamic pages in order to create static files for them, also providing a way to define the filename for each.
In the nuxt.config.js file there’s the generate property that serves for that purpose:
generate: {
    routes () {
      return axios.get('https://jsonplaceholder.typicode.com/posts')
        .then((res) => {
          var rts = []
          res.data.forEach((d) => {
            rts.push('/article/' + d.id)
          })
          return rts
        })
    }
}
In this case, the id will be used for the filename but you are free to implement different logic.
You can check the source on Github and navigate the prototype as well.

Conclusion

Keep in mind that this is a SPA (Single Page Application) with SEO (Search Engine Optimization) capability. Isn’t that awesome?
Furthermore, this is a POC (Proof Of Concept) just to learn Nuxt.js.
There is also a Nuxt blog module for those who want something more refined.
Cheers.

Directory Structure

The Assets Directory

The assets directory contains your un-compiled assets such as Less, Sass or JavaScript.

The Components Directory

The components directory contains your Vue.js Components. Nuxt.js doesn't supercharge the data method on these components.

The Layouts Directory

The layouts directory contains your Application Layouts.
This directory cannot be renamed.

The Middleware Directory

The middleware directory contains your Application Middleware. Middleware lets you define custom functions that can be run before rendering either a page or a group of pages (layouts).

The Pages Directory

The pages directory contains your Application Views and Routes. The framework reads all the .vue files inside this directory and creates the application router.
This directory cannot be renamed.

The Plugins Directory

The plugins directory contains your Javascript plugins that you want to run before instantiating the root Vue.js Application.

The Static Directory

The static directory contains your static files. Each file inside this directory is mapped to /.
Example: /static/robots.txt is mapped as /robots.txt
This directory cannot be renamed.

The Store Directory

The store directory contains your Vuex Store files. The Vuex Store option is implemented in the Nuxt.js framework. Creating an index.js file in this directory enables the option in the framework automatically.
This directory cannot be renamed.

The nuxt.config.js File

The nuxt.config.js file contains your Nuxt.js custom configuration.
This file can not be renamed.

The package.json File

The package.json file contains your Application dependencies and scripts.
This file can not be renamed.

Aliases

ALIASDIRECTORY
~ or @srcDir
~~ or @@rootDir
By default, srcDir is the same as rootDir.
Info: Inside your vue templates, if you need to link to your assets or static directory, use ~/assets/your_image.png and ~/static/your_image.png.

Thursday, October 4, 2018

Installation

Nuxt.js is really easy to get started with. A simple project only needs the nuxt dependency.

Using create-nuxt-app

To get started quickly, the Nuxt.js team has created scaffolding tool create-nuxt-app.
Make sure you have npx installed (npx is shipped by default since NPM 5.2.0)
$ npx create-nuxt-app <project-name>
Or with yarn:
yarn create nuxt-app <my-project>
It will ask you some questions:
  1. Choose between integrated server-side frameworks:
  2. Choose your favorite UI framework:
  3. The Nuxt mode you want (Universal or SPA)
  4. Add axios module to make HTTP request easily into your application.
  5. Add EsLint to Lint your code on save.
  6. Add Prettier to prettify your code on save.
When answered, it will install all the dependencies so the next step is to launch the project with:
$ npm run dev
The application is now running on http://localhost:3000.
Nuxt.js will listen for file changes inside the pages directory, so there is no need to restart the application when adding new pages.
To discover more about the directory structure of the project: Directory Structure Documentation.

Starting from scratch

Creating a Nuxt.js application from scratch is also really easy, it only needs 1 file and 1 directory. Let's create an empty directory to start working on the application:
$ mkdir <project-name>
$ cd <project-name>
Info: replace <project-name> by the name of the project.

The package.json

The project needs a package.json file to specify how to start nuxt:
{
  "name": "my-app",
  "scripts": {
    "dev": "nuxt"
  }
}
scripts will launch Nuxt.js via npm run dev.

Installing nuxt

Once the package.json has been created, add nuxt to the project via npm:
npm install --save nuxt

The pages directory

Nuxt.js will transform every *.vue file inside the pages directory as a route for the application.
Create the pages directory:
$ mkdir pages
then create the first page in pages/index.vue:
<template>
  <h1>Hello world!</h1>
</template>
and launch the project with:
$ npm run dev
The application is now running on http://localhost:3000.
Nuxt.js will listen for file changes inside the pages directory, so there is no need to restart the application when adding new pages.

nuxt