Nuxt.js can solve the problem of SEO optimization + long loading time of the first screen in vue project

In practice, simple projects use nuxTJS’s default routing rules

In complex projects, however, using nuxTJS’s default routing rules can become cumbersome, so in complex projects, nuxTJS routing rules are usually manually configured

Configure nuxTJS routing rules manually:

1. Create a new file named nuxt.config.js in the root directory of the project (the same level as package.json)

2. Enter the following code in the nuxt.config.js file:

export default {

  plugins: ['~/plugins/formatDate.js'.'~/plugins/apiConfig.js'].// The method to add the plug-in to nuxt.js
  
   // The configuration that takes place when the project is deployed to the server
  server: {
    host: '0.0.0.0'.port: 3000,},router: {
  	linkExactActiveClass: 'active'.// The 
      
        tag defaults to active class strict mode
      
    // Define nuxtJS routing rules
    extendRoutes(routes, resolve) {
      // Clear routing table rules generated by nuxt.js based on the pages directory by default
      // Delete all default routing rules in nuxtjs
      routes.splice(0)
      // Add your own routing rules to nuxtJS to use. The structure is the same as vue's original routing structure
      routes.push(
        ...[
          {
            path: '/'.component: resolve(__dirname, 'pages/layout/'), // The page component in nuxtjs
            children: [{path: ' '.// Default child route
                name: 'home'.component: resolve(__dirname, 'pages/home/'), // The subcomponent wrapped by the page component in nuxtJS (routing component)},],},])},},}Copy the code

Nuxtjs monitors changes in the address bar, and nuxtJS’s native asyncData method is called when changes occur

Add watchQuery:[] to the vue file, the same as the vue lifecycle

watchQuery: ['tab'.'tag'.'page'].// That's the point
mounted() {}, // Lifecycle - after mount
Copy the code

Use of middleware in NuxtJS

Create a new folder under the root of your project: Middleware

The js files in the Middleware folder are middleware files that are automatically executed when the corresponding page loads

For example, to create a new file called authenticated. Js, run the following code:

// Verify whether the middleware is logged in ==> Already logged in
// If you are logged in, redirect it to the home page
// Solve the problem caused by manually changing the URL of the route: After the user has logged in, the user can still go to the login page after manually changing the URL of the address bar

export default function({ store, redirect }) {
  // If the user is not authenticated
  if (store.state.users) {
    return redirect('/')}}Copy the code

Next add the following code to the corresponding login.vue page:

Mounted () {}Copy the code

If the user has already logged in, use NuxtJS to jump to the home page

Use of plug-ins in NuxtJS

Create a new folder in the root directory of your project: plugins

In NuxtJS plug-ins are called before the Vue instance is created

For example, you can wear a plug-in that formats all the dates in your project

Create a new file: formatDate.js in the plugins folder, with the following code:

Import Vue from 'Vue' import dayjs from 'dayjs' // Globally define the filter Vue. Filter ('formatDate', function(value, format = 'YYYY-MM-DD HH:mm:ss') { return dayjs(value).format(format) })Copy the code

Next, in the corresponding VUE file, write the following code where there is date data:

{{article.createdAt | formatDate('MMMM DD,YYYY') }} 

Copy the code

Finally, nuxt.config.js is required to be configured as follows:

export default {
   plugins: ['~/plugins/formatDate.js'.'~/plugins/apiConfig.js'].// The method to add the plug-in to nuxt.js
}
Copy the code

This way, the plug-in is automatically invoked before the Vue instance is created

Nuxtjs projects publish deployment on the server side -> the easiest way to deploy a project

  • (1) Configure host+port (nuxt.vonfig.js file)
Server: {host: '0.0.0.0', port:3000},Copy the code
  • (2) Compress the release package to compress some files of the packaged project, including:

.nuxt folder Static folder nuxt.config.js file package.json file package-lock.json file

The above several files, folders, compression, and then the compression package to the server side

  • (3) Send the release package to the server (XFTP software, git software, Linux command in Xshell)

(3-1) Connect to a remote server on your own computer

SSH root@IP address of the server

Create a folder in the root directory of the remote server:

Mkdir realworld-nuxtjs CD realworld-nuxtjs PWD ->/root/realworld-nuxtjs Realworld -nuxtjs. Zip root@ IP address of the server :/root/realworld-nuxtjs (transmits the compressed package to the server) SSH IP address of the root server CD Realworld – Nuxtjs ls (Check if the upload was successful)

  • (4) Decompress the software on the server

Unzip /realworld-nuxtjs.zip (unzip command is used to decompress. Zip files) ls -a (Check whether the decompression is successful)

  • (5) Install dependencies on the server

-bash: NPM: Command not found

Links:How to install and use NVM on a CentOS 8 server

  • (6) Start the service on the server to see the effect

NPM run start server IP address: port number

Link 1, Centos7 open and view the port connection link 2, FirewallD is not running problem solving link 3, Warning: solving allowzonedrifting is enabled. This is considered an insecure configuration option.It will be removed in a future release … ling it now.

The NuxtJS project publishes the deployment on the server side -> Start the Node service using PM2

In this way, the project started on the server side will occupy the command line, but the command line window is closed or the command exit, the project is not accessible. To solve this problem, we can run the project in the server background process, so we need to use the PM2 tool

Start the server project using PM2

Pm2 githup storage address: github.com/Unitech/pm2 Official document: Pm2. IO /

  • (1) Install the PM2 on the server

npm install –global pm2

  • [pm2 start script path/start project NPM command]

Run in the project folder: pm2 start NPM — start

  • (3) Enter Server IP address: port number in the browser to view the result

IP address of the server: port number

  • (4) Close the pM2 started project on the server

Pm2 stop 0 pm2 stop NPM pm2 stop NPM pm2 stop 0 pm2 stop NPM

  • (5) Common PM2 commands

Nuxtjs project release deployment on the server side -> Modern Deployment -> Automated Deployment (CI/CD)

CI/CD

Jenkins\Gitlab CI\GitHub Actions\Travis CI\ Circle CI…

Environment to prepare

  • (1) There is a server with A Linux system
  • (2) Submit the code to GitHub remote repository
  • (3) Configure the GitHub Access Token as follows:

Generate tokens for projects

  • Log in to Github –> Click on your profile picture in the upper right corner. Select Settings –> Developer Settings –> Personal Access Tokens –> Generate New Token Generate New in the upper right corner A screenshot of the Token page is as follows:

Then a token will be generated (screenshot below), this token should be saved, because it will not be seen in the later stage. If not saved, it will be forgotten in the later stage, and you will have to generate a new token

Go to your Github project, click the Settings button, click the Secrets button in the lower left corner of the page, Click the New Repository Secret button in the upper right corner of the page.

  • (4) Configure GitHub Actions to execute scripts

Create the. Github /workflows directory under the root directory of the project. Create the main.yml file to the workflows directory.

  • (5) In the root directory of the project, configure the PM2 configuration file named [pm2.config.json], the code is as follows:
{
 "apps": [{"name": "RealWorld"."script": "npm"."args": "start"}}]Copy the code
  • (6) Commit the local code to the remote repository

Git add. Git commit -m

  • (7) Commit updates to start automated deployment

Git push Origin v0.1.0 git push Origin v0.1.0

  • (8) View the progress and status of automatic deployment

Click the Actions button within the Github project to check it out

After the Aaction button is clicked, the screenshot of the page is as follows, indicating that the automatic deployment is successful:

  • (9) Visit the website

IP address of the server: port number

  • (10) The project is adjusted and repeated (6) ~(10)

Ssh_exchange_identification: read: Connection reset by peer

  • Solution: to try www.jianshu.com/p/84dce4701…
  • Solution: to try www.cnblogs.com/Tanwheey/p/…
  • Another possibility is that your company’s network is limited and you can only use your phone’s data to test if you can successfully log in

Digression: CentOS recycle bin directory should be the path: CD ~ / local/share/Trash/files/this path is a hidden attribute to delete all the files in a directory of the command: rm – rf *