Stage 5: Vue Advancement

# 1 Vue Exercise ## 1.1 Exercise: Show different web addresses according to different elements
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Practice vue Route</title>
		<script src="vue/vue.js"></script>
		<script src="vue/vue-router.js"></script>
	</head>
	<body>
		<!-- demand:Click on different elements,Show different web addresses -->
		<div id="app">
			<router-link to="/runoob">runoob</router-link>
			<router-link to="/w3c">w3c</router-link>
			<router-view></router-view>
		</div>
		<script>
			let router = new VueRouter({
				routes:[ //Distribute different requests to different components for processing
					{ //When you click on runoob, match the corresponding component and show the runoob's web address
						path:'/runoob',
						component:{
							template:'<h1><a href="https://www.runoob.com">https://www.runoob.com/</a></h1>',
						},
					},
					{ //When clicking on w3c, match the corresponding component and show the web address of W3C
						path:'/w3c',
						component:{
							template:'<h1><a href="https://www.w3school.com.cn">https://www.w3school.com.cn/</a></h1>',
						},
					}
				]
			})
			new Vue({
				el:"#app",
				router
			})
		</script>
	</body>
</html>

1.2 Summary

Life cycle of 1.3 Vue

When using Vue for a project, we need to understand the lifecycle and lifecycle functions of the Vue object (the process from creation to destruction of a Vue instance) so that we know what to do in which function.

For example, when a page is created, when a page is loaded, when a page is updated, and when a page is destroyed?

During this process, we trigger methods (which have some capabilities) at each specific stage, and we name these methods Lifecycle hook functions/component hooks.

Lifecycle function:

  • The vue instance executes these functions automatically at a certain point in time.
  • Lifecycle hook functions are not allowed to be written as arrow functions;

It can be divided into three phases, a total of eight hooks: Initialization phase (before/after creation, before/after loading), Running (before/after update), Destroying (before/after destruction)

Subdivide each process:

1.4 npm concept

npm (node package manager): Package manager for nodejs, used for node plug-in management (including installation, uninstallation, management dependencies, etc.)

npm opens a door for you and your team to connect to the entire JavaScript world. It is the world's largest software registry, with about 3 billion downloads per week, and contains more than 600,000 packages (i.e., code modules). Open source software developers from all continents use npm to share and learn from each other. The package structure allows you to easily track dependencies and versions.

Official website:

https://docs.npmjs.com/about-npm English official website

https://www.npmjs.cn/ Chinese official website

1.5 webpack concepts

Webpack is a front-end automation building tool, which is based on nodejs implementation, and can help us achieve many functions such as resource consolidation, packaging, compression, confusion. You can quickly build a Vue project that includes various types of files (assets resources, scripts scripts, images, styles styles).

Official website:

https://webpack.js.org/

2 Vue scaffolding

2.1 Overview

Vue scaffolding refers to vue-cli, which refers to the client of Vue. It is a fast and complex scaffolding designed for single-page applications. It can easily create new applications and can be used to automatically generate project templates for Vue and webpack, which is ahead of time for using Vue projects.
vue-cli is Vue's scaffolding tool, which provides a rich range of functions and can be used as long as the installation is successful. It's really the same thing with the scaffolding we see on the job. It helps us build a basic development environment, like a shelf that can be used to build directory structure, local debugging, unit testing, hot loading, code deployment, and so on.
The vue-cli is an official cli provided by Vue that is designed to quickly build complex scaffolding for single-page applications. It is a project template for automatically generating vue.js+webpack and provides a batteries-included architecture for modern front-end workflows. It only takes a few minutes to run with hot overloads, lint checks on save, and build versions available for production environments

2.2 Installation

2.2.1 Install nodejs, the next step is to install the latest version 15, and 14 If win7. Use the following dos command prompt to execute:

Node-v # v8.11.3, at least 8 or more, the latest is v15.11.0

2.2.2 Modify npm mirror (fast download):

npm config get registry # View the currently configured mirror and the result is the default foreign web address https://registry.npmjs.org/

npm config set registry https://Regisry.npm.taobao.org #Modify the web address of the downloaded resource to Taobao and set it as a mirror of Taobao

npm config get registry #Get the view again, and the result is modified https://registry.npm.taobao.org/ 

2.2.3 Official Installation (without a red ERR):

vue-cli: User-generated Vue project template (helps you quickly build a Vue project, that is, gives you a Vue structure with basic dependency libraries)
vue-cli: Scaffolding tool installation and configuration (takes a few minutes)

npm install vue-cli -g  #Global installation of vue scaffolding - may be slower, wait a few minutes

npm uninstall vue-cli -g #Uninstall vue-cli scaffolding - no need

vue –V #View version of scaffolding

where vue #See where the vue scaffolding is installed

2.2.4 Download/create vue project

Official webpack template based on vue.js: (unobtrusive), specify a path to the workspace to store the code for the Vue project

webpack: Its main purpose is to prepare all browser-side static resources that need to be published through the syntax of CommonJS, such as resource consolidation and packaging

Location in workspace,input cmd,Knock Enter,Enter the following command:
vue init webpack jt01  #Download project 100M+ from jt01 using scaffolding, project name cannot be capitalized here - may be slower, wait
 Configure some options,yes/no,Select an answer by referring to the picture below.


Note:
1. jt01 is a custom project name
2. Produce project webpack template, catalog 100+m, visible content is complex and bulky
3. node_will be automatically generated Modules temporary directory, can be deleted, each compile, run will automatically generate

2.2.5 Check if the vue project has been downloaded

The principle is: if you don't encounter a flushing ERR along the way, you can

2.2.6 Test Projects

Follow the prompt and execute two more commands:

cd jt08  #Enter the project folder
npm run dev  #Start the project, ctrl+c stops, maybe a few minutes
DONE  Compiled successfully in 9949ms #Indicates that the project started successfully
 Open Browser Access:http://localhost:8080

Note: The port number may be different, defaulting to 8080. If you find that the port occupies npm wisely, it will automatically change the port number, depending on the port information prompted.

2.2.7 Open the Vue project with Hbuilder

File - Open Directory - Select the vue project you just downloaded - OK

3 HBuilderX Manage Vue Project

3.1 Open the Vue project

HBuilderX is one of the latest front-end development tools, fully supporting the development of Vue, with rich tips to open: D:\workspacevue\jt01 directory (you can define your own directory)

3.2 Structure

3.4 Directory Structure

This directory structure is very important to remember. If you want your child to go to a maternal and child care center, you need to swim to the swimming pool. The way and location of each directory are agreed upon. With this set of rules, files are not messed up, so that when you look for resources, you know where to look, and when you write code files, you place them in the specified directory by function. This is already common, such as when Maven has mandatory conventions for building project directories, such as greater than configuration conventions in the Spring framework.

  • view is the directory where all the pages the user wants to access are stored, such as Index.vue
  • Static holds some static resources, such as jquery, css, pictures, etc.
  • The src directory is a large, all-inclusive directory
  • Compoonents place all the components needed in the project in this directory. By default, a HelloWorld.vue is created, which we can add ourselves, such as Header.vue
  • Router access path, Vue advocates SPA (Single Page WebApplication) single page design, which is the path problem that must be involved if other resources are included in the old pages. Html does not solve this problem very well, but router is a new invention to solve the path, which solves the multi-module page refresh problem very well. Simply put, it's about indicating a path to the component and how we access it. Different components are accessed by the configured path router. Router is very powerful, the old system is that url changes are refreshed on the server side, while router supports client-side refresh, that is, url changes, page content changes, but does not request server-side, which previous programs could not do. This is not easy to understand. We need not be in a hurry to write down this feature first.

3.5 Important Document Description

Vue project so many files, what do they matter? Where do I start writing code?
Common actions: 1, write custom component 2 in components, register custom component 3 in App.vue, and introduce third-party JS in main.js

  • index.html home page, Vue is SPA single page development, page entry, defines a div, and sets id=app
  • The public components of src/main.js are configured directly into this file and privately into the view

  • src/App.vue root component, you can add custom components,
  • src/router/index.js introduces subcomponent HellWorld.vue



Simply put, the process of loading a project is:

index.html->main.js->App.vue->index.js->HelloWorld.vue

You can see that the Vue project has its own set of rules, a set of mechanisms, and is very systematic. There are fixed files, there are custom files, each placed in a specified directory, specified files, designated places, ultimately to achieve user needs. Before you start development, you have to understand this mechanism. You write code with clear rules. If you can help, you know why you write code, where you put your code files, who called them, and how they called each other.

Why do you spend so much time talking about these files?
Many students write code, listen to the teacher say no problem, but do it yourself and mess up, blank heads are even pasty, do not know where to write the code? I don't know what to do if something went wrong. Why? Did all the teachers teach you? Even if you have not organized the knowledge system you have learned effectively, the content is only a point, which can not be well connected to form a line, first in the form of a surface, then in the form of a body. The overall process of code becomes clearer when the dot-line polygons are truly organized.

So how?

Think, but complex things don't come to mind right away. You'll be dizzy for a long time. So what to do, the real trick, hit and practice more, and slowly sum up its true law in repeated practice. Just like when we play games, a master of games is not born, but practices and failures. Failure is the mother of success. This is true.

4 Add custom components to the Vue project

4.1 Overview

Component is one of the most powerful features of Vue.js.
Components can extend HTML elements to encapsulate reusable code.
Component systems allow us to build large applications with independent reusable widgets, and the interface of almost any type of application can be abstracted into a component tree

4.2 Project Structure

4.1 Create Car.vue File - Custom Component

Location: In the src/components folder

<!-- write HTML Code -->
<template>
  <div>
    <h1>{{msg}}</h1>
  </div>
</template>
<!-- write js Code -->
<script>
// Provide a component to support export
export default{
  name:'Car' ,//Component name, usually identical to file name
  data(){   //Preparing to return data
    return{
      msg:'hello vue~~'
    }
  }
}
</script>
<!-- write css Code -->
<style>
</style>

4.2 Modify App.vue file

Introduce custom components into this file

<template>
  <div id="app">
    <!-- 3.Use custom components,Treat as HTML element-->
    <Car></Car>
  </div>
</template>
<script>
  //1. Import custom component car.vue at specified location
  import Car from './components/Car.vue'
  //2, using the components property, using custom components
export default {
  name: 'App',
  components:{
    Car //Register the custom components just imported
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>


4.3 Test

  1. The server is guaranteed to be started and new code has been compiled

  2. In the browser http://localhost:8080/ test

5 Exercise Custom Components

5.1 Create a component for person.vue

<template>
  <div>{{name}}</div>
</template>

<script>
export default{
  name:'person',
  data(){
    return{
      name:'jack'
    }
  }
}
</script>

<style>
</style>


5.2 Modify App.vue to introduce custom components

<template>
  <div id="app">
    <!-- 3.Use custom components,Treat as HTML element-->
    <Car></Car>
    <person></person>
  </div>
</template>
<script>
  //1. Import custom component car.vue at specified location
  import Car from './components/Car.vue'
  import person from './components/person.vue'
  //2, using the components property, using custom components
export default {
  name: 'App',
  components:{
    Car , //Register the custom components just imported
    person
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>


5.3 Test

  1. Knock Enter in the DOS window (to automatically compile new code)
  2. Open browser, refresh to see new data http://localhost:8080

6 ElementUI

6.1 Overview

Element provides a beautiful set of front-end web pages

Visit the official website: https://element.eleme.cn/#/zh-CN/component/installation, view component Guide

6.2 Steps to use

  1. In the current project, download the tool for element-ui

npm i element-ui -S  #Install element-ui
  1. Check download results

6.3 Modify main.js to introduce elementui

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

//Introduce third-party ElementUI to beautify pages
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})


6.4 Layout layout

Raster system: Pages are divided into 24 columns to form PC-side and mobile-side adaptive.

<template>
  <div>
<!-- 2.Use ele Raster of,Default 24 columns,Adaptable screen width -->
<!-- el-row Represents a row,el-col Representation Column ,:span Number of merged columns-->
  <el-row> 
    <el-col :span="24">123</el-col>
  </el-row>
  <el-row>
    <el-col :span="12">abc</el-col>
    <el-col :span="12">123</el-col>
  </el-row>

  </div>
</template>

<script>
  // Define Exported Components
  export default{
    name:'Item',
    data(){
      return{
        msg:'Beijing Taobao E-commerce Management System'
      }
    }
  }
</script>

<style>
</style>


6.5 icon Icon

https://element.eleme.cn/#/zh-CN/component/icon

<template>
  <!-- Get value -->
  <div>
    <!-- 1.Use ele Various icons-->
     <i class="el-icon-edit"></i>
     <i class="el-icon-share"></i>
     <i class="el-icon-delete"></i>
     <i class="el-icon-eleme"></i>
  
  </div>
</template>

<script>
  // Define Exported Components
  export default{
    name:'Item',
    data(){
      return{
        msg:'Beijing Taobao E-commerce Management System'
      }
    }
  }
</script>

<style>
</style>


6.6 Button button

https://element.eleme.cn/#/zh-CN/component/button

<template>
  <!-- Get value -->
  <div>
    <!-- 1.Use ele Various buttons-->
     <el-button type="primary" icon="el-icon-search">search</el-button>
<el-button>Default button</el-button>
      <el-button type="primary">Main Button</el-button>
      <el-button type="success">Success button</el-button>
      <el-button type="info">Information Button</el-button>
      <el-button type="warning">Warning button</el-button>
      <el-button type="danger">Danger Button</el-button>
  
  </div>
</template>

<script>
  // Define Exported Components
  export default{
    name:'Item',
    data(){
      return{
        msg:'Beijing Taobao E-commerce Management System'
      }
    }
  }
</script>

<style>
</style>


6.7 input Box

  <el-input placeholder="User name" v-model="msg"></el-input>
  <el-input placeholder="Password" v-model="msg" show-password></el-input>


<script>
export default {
  data() {
    return {
      input: ''
    }
  }
}
</script>


6.8 table

https://element.eleme.cn/#/zh-CN/component/table

<template>
  <!-- Get value -->
  <div>
    
    <!-- 3.Use ele Table,a Create tables,b Preparing data,c Binding data -->
    <el-row >
      <el-button type="info" @click="toadd">Newly added</el-button>
    </el-row>
  	<el-table :data="list">
       <el-table-column label="number" prop="id"></el-table-column>
       <el-table-column label="Title" prop="title"></el-table-column>
       <el-table-column label="selling point" prop="sell"></el-table-column>
       <el-table-column label="describe" prop="desc"></el-table-column>
       <el-table-column label="More">
          <el-button type="primary" @click="toupdate()">edit</el-button>
          <el-button type="success" @click="del()">delete</el-button>
       </el-table-column>
     </el-table>
  </div>
</template>

<script>
  // Define Exported Components
  export default{
    name:'Item',
    data(){
      return{
        msg:'Beijing Taobao E-commerce Management System',
        // b. Prepare the data for the form
         list:[
          {
            id:100,
            title:'Erke',
            sell:'For China',
            desc:'to be no.1'
          },
          {
            id:101,
            title:'Honey Snow Ice City',
            sell:'Make only 1 dime a bottle',
            desc:'You love me I love you Honey Snow Ice City Sweet'
          },
          {
            id:102,
            title:'XTEP',
            sell:'There's a step.Feeling',
            desc:'Feeling like flying'
          }
        ]
      }
    },
   // 1, declare button 2, add event methods 3, bind event@click to button
    methods:{
        toadd:function(){
          console.log("New business success")
        },
        toupdate:function(){
          console.log("Successful business modification")
        },
        del:function(){
          console.log("Delete succeeded")
        }
      }
  }
</script>

<style>
</style>


6.9 Form

https://element.eleme.cn/#/zh-CN/component/form

<template>
  <!-- Get value -->
  <div>
	<!-- Make a Form el-form Represent Form,el-form-item Represents a form item
1,Data area provides data 2,to form Specify bi-directional binding:model="form" 3,input Bidirectional Binding to Get Data v-model="form.price"
  -->
    <el-form label-width="100px" :model="form">
    <el-form-item label="Title">
      <el-input placeholder="Please enter a title" v-model="form.title"></el-input>
    </el-form-item>
    <el-form-item label="selling point">
      <el-input v-model="form.sell"></el-input>
    </el-form-item>
    <el-form-item label="Price">
      <el-input v-model="form.price"></el-input>
    </el-form-item>
    <el-form-item label="details">
      <el-input type="textarea" v-model="form.desc"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button @click="save()" type="success">Preservation</el-button>
    </el-form-item>
  </el-form>

    </div>
</template>

<script>
  // Define Exported Components
  export default{
    name:'Item',
    data(){
      return{
        msg:'Beijing Taobao E-commerce Management System',
        //Preparing data for forms, data-driven, two-way binding
        msg:'hi components',
        form:{
          title:"test",
          sell:'Explosive Hot Sales',
          price:999,
          desc:"I am Detail..."
        },
      }
    },
   // 1, declare button 2, add event methods 3, bind event@click to button
    methods:{
      save:function(){ //Form Submission
        // console.log("submit")
        console.log(this.m) //Call the variable m above
      }
      }
  }
</script>

<style>
</style>


6.10 Test, modify custom component person.vue/car.vue

<!-- write HTML Code -->
<template>
  <div>
    <h1>{{msg}}</h1>

    <!-- 1.Button -->
    <el-button type="success">Success button</el-button>
    <el-button type="danger" icon="el-icon-delete" circle></el-button>
    <!-- 2.layout,Default 24 points per line,Free Combination
      :span Attribute represents merged columns,el-row Represents row elements,el-col Represents column elements
    -->
    <el-row>
      <el-col :span="2">123</el-col>
      <el-col :span="12">456</el-col>
    </el-row>
    <!-- 3.Icon,i Elements representing icon pages,class Property specifies which icon to use-->
    <i class="el-icon-share"></i>
    <i class="el-icon-s-flag"></i>
    <!-- 4.Button,el-button Button effect,type Set Colors,circle circular,icon Add an icon to the button-->
    <el-button type="success" round icon="el-icon-search">Register Now</el-button>
    <el-button type="success" circle icon="el-icon-delete"></el-button>

  </div>
</template>
<!-- write js Code -->
<script>
// Provide a component to support export
export default{
  name:'Car' , //Component name, usually identical to file name
  data(){   //Preparing to return data
    return{
      msg:'hello vue~~'
    }
  }
}
</script>
<!-- write css Code -->
<style>
</style>


6.11 Common Errors

Permission denied
Insufficient privileges, windows runs as administrator with sudo before mac commandUnexpected end of JSON input while parsing near

Clear cache, reinstall

npm cache clean --force

npm install

unable to verify the first certificate

Solution: Cancel SSL validation: npm config set strict-ssl false, install again

vue-cli · Failed to download repo vuejs-templates/webpack: unable to verify the first certificate


Open (if not the default folder, or a custom folder path, in the directory of the custom folder)

C:\Users\Administrator\AppData\Roaming\npm\node_modules\vue-cli\node_modules\download\index.js 
Comment on the following line: rejectUnauthorized: process.env.npm_config_strict_ssl !== 'false'
Then change to:  rejectUnauthorized : false    
Rerun:  vue init webpack project-name  That's it

Tags: Javascript Front-end Vue.js

Posted on Wed, 20 Oct 2021 12:31:11 -0400 by michaelfn