Initialize the project

Nuxt’s scaffolding tool allows you to quickly create a project. When creating a project, you can make some choices, such as selecting the integrated server framework, selecting the UI framework and so on.

NPX is installed in NPM version 5.2.0 by default. NPX create-nuxt-app < project name >Copy the code

thennpm run devYou can start the project locally

You can also create a new project from scratch.

// Create project folder mkdir nuxt-demo // enter project CD nuxt-demo // initialize project NPM init // install nuxt NPM install --save nuxtCopy the code

Ii. Project directory structure

Nuxt’s default directory architecture provides good code layering.

Nuxt basic configuration

The nuxt.js default configuration covers most usage scenarios and can be overridden with nuxt.config.js

4. Route configuration and parameter transfer

Nuxt automatically generates routing module configurations based on the pages directory structure. Assume that the directory structure of pages is as follows

pages/
--| user/
-----| index.vue
-----| one.vue
--| index.vue
Copy the code

The automatically generated route configuration is as follows

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'user',
      path: '/user',
      component: 'pages/user/index.vue'
    },
    {
      name: 'user-one',
      path: '/user/one',
      component: 'pages/user/one.vue'
    }
  ]
}
Copy the code

Available for direct use

<template> <nuxt-link to="/">Copy the code

Nuxt.js defines dynamic routes with parameters. You need to create a Vue file or directory with an underscore as the prefix, for example, id. Vue. In this file, id is the dynamic route parameter, which can be received in the component according to this.

// user/index.vue <template> <div class="container"> <div> /user home <ul> <li><nuxt-link to="/user/1">user1</nuxt-link></li> <li><nuxt-link to="/user/2">user2</nuxt-link></li> <li><nuxt-link to="/user/3">user3</nuxt-link></li> </ul> </div> </div> </template> <script> export default { } </script> <style> .container{ background: skyblue } </style>Copy the code
Vue <template> <div class="container"> <h1> id:{{id}} </h1> <div> {{user.name}} </div> </div> </template> <script> export default { data(){ return { id:this.$route.params.id, Users: [{id: 1, name: 'Joe'}, {id: 2, name: 'bill'}, {id: 3, name: 'Cathy'}]}}, computed:{ user(){ return this.users.find(user => user.id == this.id) } } } </script>Copy the code

5. Nuxt routing animation effect

Global Settings If you want to set dynamic effects for each route switch, you can create a common CSS file. You can create a router. CSS under assets/ and add it to nuxt.config.js

// assest/css/router.css
.page-enter-active, .page-leave-active {
  transition: opacity .5s;
}
.page-enter, .page-leave-active {
  opacity: 0;
}
Copy the code
css:['assets/css/router.css'],
Copy the code

If some routes do not take effect, they are not used for redirecting.

If you want to customize the transition effect for a page, simply configure the Transition field in the page component and add it to router.css

.test-enter-active, .test-leave-active {
  transition: opacity .5s;
}
.test-enter, .test-leave-active {
  opacity: 0;
}
Copy the code

We then set the transition property in the page component to test

export default {
  transition: 'test'
}
Copy the code

We can customize the template file by creating app.html in the root directory of the project. We can customize it.

<! DOCTYPE html> <html> <head> {{ HEAD }} </head> <body> <h3>nuxt-demo</h3> {{ APP }} </body> </html>Copy the code

Note that HEAD and APP can not be lowercase, otherwise an error will be reported. When creating app.html, you need to restart it, otherwise it will not take effect.

In the layouts folder, there is a default. Vue, which is the content of each of our pages. We can modify default.vue to meet layout requirements.

<template> <div> <h1> Default layout </h1> <nuxt /> </div> </template>Copy the code

Error pages can be customized by editing layouts/error.vue

<template> <div class="container"> <h1 v-if="error. StatusCode === 404"> The page does not exist </ H1 > < H1 V -else> Application error </ H1 > <nuxt-link To ="/"> 后 页</nuxt-link> </div> </template> <script> export default {props: ['error'], layout: 'blog' // You can specify custom layout for error pages} </script>Copy the code

Templates and layouts can be used together to better complete projects. For example, you can set header information in the template and achieve unified layout in default.vue.

Set the meta

We can set a uniform meta in nuxt.config.

You can also add Settings in the component page

<template> <div class="container"> <div> /user home <ul> <li><nuxt-link to="/user/1">user1</nuxt-link></li> <li><nuxt-link to="/user/2">user2</nuxt-link></li> <li><nuxt-link to="/user/3">user3</nuxt-link></li> </ul> </div> </div> </template> <script> export default {head(){return{title:' user home ', meta:[ {hid:'description',name:'user',content:'This is user page'} ] } } } </script>Copy the code

Ps: common configuration items of other components

7. Data acquisition

In NUXT, it is recommended to use Axios for data requests.

Within a component, we can make data requests in asyncData methods, allowing us to asynchronously fetch or process data before setting the component’s data.

When this method is called, the first argument is set to the context object for the current page

Nuxt.js returns the data returned by asyncData’s data fusion component method to the current component

Note: Since the asyncData method is called before the component is initialized, there is no way to refer to the component instance object through this within the method.

Nuxt.js provides several different ways to use asyncData methods

  1. Returns aPromise, nuxt.js will wait for thatPromiseAfter it is parsed, the component’s data is set to render the component.
  2. Use async or await

Return to the promise

export default {
  asyncData ({ params }) {
    return axios.get(`https://my-api/posts/${params.id}`)
      .then((res) => {
        return { title: res.data.title }
      })
  }
}
Copy the code

Use async or await

export default {
  async asyncData ({ params }) {
    const { data } = await axios.get(`https://my-api/posts/${params.id}`)
    return { title: data.title }
  }
}
Copy the code

The data fusion

data () {
    return { foo: 'bar' }
  }
Copy the code

Available directly on components

<template>
  <h1>{{ title }}</h1>
  <p>{{foo}}</p>
</template>
Copy the code

Note that there are many attributes in context objects that can be directly deconstructed and applied to projects. Here are some of the most common ones

export default { async asyncData ({ app , store , query ,params }) { // app : // query: route.query // params: route.params}Copy the code

Static resource import

If your static assets require Webpack to build and compile them, you can put them in Assets, otherwise you can put them in static

By default, Nuxt uses vue-loader, file-loader, and url-loader to handle file loading and referencing.

Starting with Nuxt 2.0, /alias will not resolve correctly in CSS files. You must use assets (without slashes) or @ aliases in URL CSS references, i.e. background: URL (“~assets/banner.svg”)

<template>
  <img src="~/assets/image.png">
</template>
Copy the code

Of course, there are also middleware and plug-ins, which are very simple and useful, and you can check them out in the official documentation

In fact, vue based, NuxT is very simple to use, and the performance is good, Chrome ran a point for reference only.