1 the introduction

Nuxt is a front-end development framework based on Vue. This time we will learn about the features of the framework and the basic elements of the front-end development framework through the Introduction toNuxtJS video.

Nuxt is similar to the next structure and can be viewed together

The video introduces NuxtJs installation, directory structure, page routing, navigation templates, asyncData, Meta, vueX.

This is an entry level video, so the features listed above are the core building blocks of a front-end development framework. A front-end development framework, installation, directory structure, page routing, navigation templates must be the most serious effort to design.

AsyncData and Vuex both solve data problems, while META controls meta properties of web pages through convention syntax. This part is worth comparing with React system and will be expanded in the intensive reading part.

Nuxtjs front-end development framework not only provides the basic functions of scaffolding, but also makes conventions on the project structure and code to reduce the amount of code. From this point of view, scaffolding always revolves around two core goals: having each line of source code describe business logic; Make each project structurally identical and readable.

Twenty years ago, a few hundred lines of HTML, Css, and Js code could complete a complete project. All you needed to do was follow the basic W3C specifications. Each project code was simple and clear, and the structure of the code was very simple because there was no complex business logic. But now front project complexity increases, a large project could reach hundreds of thousands, millions of lines of source code number, it is not envisaged that the W3C specification, hence the complexity of various engineering and modular solution to solve this problem, also caused each framework agreement between split, and different degree of reasonable design.

What frameworks like Nuxtjs do is define front-end development standards that support modern large-scale projects. This specification has network effects, and the more people use it, the more value it has.

Let’s get down to business and see what development specifications Nuxt scaffolding defines.

2 an overview

The installation

Create a new project using NPX create-nuxt-app app-name. This command is the same as create-react-app except for the template and configuration.

This command essentially pulls a template locally, installs the NuxT series of scripts as project dependencies, and automatically generates a series of npmScripts:

{
  "scripts": {
    "dev": "nuxt"."build": "nuxt build"."start": "nuxt start"."generate": "nuxt generate"."lint": "eslint --ext .js,.vue --ignore-path .gitignore ."."test": "jest"
  },
  "dependencies": {
    "nuxt": "^ 2.0.0." "}}Copy the code

The project can then be developed using commands such as NPM start. For most projects, NPM Scripts is the most consensual startup.

Another benefit of this setup is that the dependencies are installed locally, meaning that the development environment is built 100% into the project. Nuxt does not use global CLI command execution, first, npmScripts is more in line with common habits, do not need to remember different scaffolding cumbersome names and different conventions of the start command, second, global scaffolding once incompatible upgrades, old projects will face maintenance problems.

The directory structure

Heavy Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal Metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metal metalCopy the code

pages

The directory where the page file is stored, the path + the file name is the route name. For more information about the convention route, see the routing page in the next section.

layouts

The name of the template file is the template name. You can select a template by defining a template.

store

Global data flow directory, described in the vueX section.

Assets, the static

Separate resource files that do not need to be compiled from non-.vue static files such as SCSS files.

Since.vue files integrate HTML, JS, and CSS, there is no need to define additional style files in the static folder.

Of course, this is a special feature of the Vue ecosystem. In the React ecosystem, there are a large number of.scss files mixed in various directories, which makes reading difficult.

Middleware, plugins,

Middleware and plug-ins, these two directories are optional as a customization extension capability.

.nuxt

To enable convenient features such as convention routing, some files need to be automatically generated when starting a project as the real project entry. These files are stored in the.nuxt directory, gitingore, and do not need to be manually modified.

nuxt.config.js

Nuxt uses a JS file as a configuration file, which is more extensible than a JSON configuration file, and is the only configuration file for the entire project.

Pages, layouts, Store, Assets, and unique configuration files are standard parts of modern front-end development frameworks.

Page routing

Nuxt supports convention routing:

├── Pages │ ├─ home. ├─ indexCopy the code

The directory structure above describes two routes: / and /home.

Parameter routing is also supported. You can define a dynamic parameter route by prefixing the file with an underscore:

├── Pages │ ├─ Videos │ ├─ ├.vueCopy the code

/videos/* will point to the file, and the url parameter can be obtained by using $route.params.id.

Another feature is nested routines by:

├ ─ ─ pages │ ├ ─ ─ videos │ │ └ ─ ─ index. The vue │ └ ─ ─ videos. VueCopy the code

Videos. Vue and videos/index.vue both point to the route /videos. If these two files exist at the same time, then the outer videos will block all routes under the /videos folder. Child elements can be exposed via nuxt-child:

# pages/videos.vue
<template>
  <div>
    videos
    <nuxt-child />
  </div>
</template>
Copy the code

Navigation template

Common page logic, such as a navigation bar, can be placed in a template directory under the layouts folder.

The default layouts/default.vue will work for all layouts, but you can also create a special navigational file such as layouts/ Videos.

<script>
  export default {
    layout: "videos"
  };
</script>
Copy the code

asyncData

AsyncData is an asynchronous fetch function supported by NUXT that can replace data.

The data function:

<script>
  export default {
    data() {
      return{}; }};</script>
Copy the code

For asynchronous scenarios, asyncData can be used instead:

<script>
  export default {
    async asyncData() {
      return await fetch("/"); }};</script>
Copy the code

meta

Nuxt allows you to customize the head tag information in.vue page files:

<script>
  export default {
    headr() {
      return {
        title: "".meta: {
          charset: "utf-8"}}; }};</script>
Copy the code

This is a feature provided by the framework, but in React you can fix this problem by using custom Hooks such as useTitle to reduce the framework functionality to code functionality, which is easier to understand.

vueX

Nuxt integrates with Vuex to create data models under store/ folder:

export const state = (a)= > ({
  videos: [].currentVideo: {}})export const mutations = {
  SET_VIDEOS (state, videos) {
    state.videos = videos
  }
  SET_CURRENT_VIDEO (state, video) {
    state.currentVideo = video
  }
}
Copy the code

Then you can use the page component in the Pages folder:

<script>
  import { mapState } from "vuex";

  export default {
    async fetch({ $axios, params, store }) {
      const reponse = await $axios.get(`/videos/${params.id}`);
      const video = response.data.data.arrtibutes;
      store.commit("SET_CURRENT_VIDEO", video); }};</script>
Copy the code

Replace return with store.mit. Refer to the vuex documentation for more syntax.

3 intensive reading

The Nuxtjs framework does several things:

  1. Execute commands in a unified manner.
  2. Unified development framework.
  3. Unified catalog and code specification.
  4. Built-in public utils functions.

Unified execution command

The command line is something all developers use a dozen or even dozens of times a day. Imagine a team with so many different startup commands for each project.

  1. npm start.
  2. monkey dev.
  3. npm run ng.
  4. npm run bootstrap & banana start.
  5. .

I never know how I’m going to get the next project off the ground, which slows things down a lot. More seriously, some projects can view documents through NPM Run Docs, others can’t; Some projects have NPM run builds that trigger compilations, others don’t, etc. The so-called environment inconsistency or migration cost, learning cost, is all caused by the students who were responsible for building the scaffolding of the project in the first place. However, there are no projects that need monkey Dev to run. But projects that are designed to be launched as Monkey Dev can be out of step with other projects, or even hard to maintain.

Front-end development frameworks such as Nuxtjs are designed to solve this problem by implementing unified commands. Unified developers are used to taking a long time, but the trend is unstoppable.

Unified Development Framework

While the React, Vue, and Angular frameworks have their pros and cons, no one thinks it’s a good thing if a team uses more than two frameworks on a project.

Admittedly, each framework has its own characteristics and has some advantages in different dimensions, but the coexistence of the three frameworks shows that neither of them has an absolute killer card to eliminate the other.

Diversity is a source of vitality for open source, but it’s a disaster for a company, and no framework can claim the advantage of “mixing with other frameworks to improve overall development efficiency.”

This is also the most important problem that the front-end development framework has to solve. In any case, only one development framework can be chosen. Nuxtjs chose Vue and Nextjs chose React.

Unified catalog and code specification

Directories and code specifications do not fundamentally affect the universality of a project, because different directory structures can be mapped to be compatible, and different code specifications do not affect code execution. So what directories and code specifications really affect is a programmer’s “decoding cost” of a project.

The so-called decoding cost is the cost that programmers need to understand the project logic. If you’re a sales executive, it’s much more efficient to have your team’s weekly reports put together in one format than it is to “put them together the way you like.” The same goes for programming, where a completely different directory structure and code specification is a huge barrier to reading for programmers, and can lead to nausea.

So different directory structures and code specifications are unnecessary barriers, and unless your team already has a solid consensus on a specification, it’s best to share the same directory structures and code specifications with other teams. Changing a code specification is a hard thing to do, but once there is a long-term relationship between teams with different specifications, uniformity is bound to be on the agenda, so why not reach an agreement at the company level earlier and take the pain out of it?

In many cases, don’t question why a directory is called layout, because the larger the collaborative network behind it, the less important its name is.

Built-in public utils functions

Making business development more focused can also be done by extracting common logic, but two problems need to be solved:

  1. Although splitting common functions into NPM packages can solve the code reuse problem, the key is how to ensure that your code can be reused by others?
  2. How can business common Utils code be effectively precipitated and removed from a project?

Scaffolding has built-in public utils functions to solve this problem. The above sections have solved the general commands, frameworks and specifications. However, in the actual code, concepts such as router History Fetch Store can also be unified. No project has to use a customized FETCH function to fetch numbers. But customizing fetch from the start leads to coupling unexpected and unnecessary business logic, which becomes a barrier to understanding and performance.

Therefore, the unification of these unified packages is the key to further improve efficiency. Maybe someone will think broke his to make the way of the wheel, but as we now will not rewrite the browser kernel logic, the stability of the logic is not only bring the effect of the whole industry, it has also created a front position brings a large number of employment, in the same way, unified the underlying generic functions, this road is actually broken meaningless output, everyone has the right to the pursuit of higher value things, Don’t trap yourself in the low-level work of repeatedly making fetch functions.

4 summarizes

If a project does not use a development framework like Nuxtjs, it will not only face the problem of inconsistent technology selection, but over time such a project is bound to become an island of code. After several years in the code repository, a series of documentation tool links fail, it will become high-risk code that no one wants to touch, dare not touch.

So today we want to see not only how convenient the capabilities Nuxtjs provides are for project development, but also how great the synergies of such frameworks can be, if not the standard for the entire front end, then at least for your company, or your team.

The discussion is at Nuxtjs · Issue #213 · dT-fe /weekly

If you’d like to participate in the discussion, pleaseClick here to, with a new theme every week, released on weekends or Mondays. Front end Intensive Reading – Helps you filter the right content.

Pay attention to the front end of intensive reading wechat public account

Copyright Notice: Freely reproduced – Non-commercial – Non-derivative – Remain signed (Creative Commons 3.0 License)