Vue’s instance, life cycle and Vue Scaffold (Vue-CLI) instance

1. Vue example

1. An instance of a Vue is created

Each Vue application is created by the Vue function to create a new Vue instance :

VAR VM = New Vue ({// Option})
  Although not fully followed by the MVVM model, Vue design is undoubtedly its inspiration. Therefore, VM (referms of ViewModel's abbreviation) is often used in the document, which represents the Vue instance.  
1, Vue.js is a constructor, instantiates an object by constructor Vue; for example: VAR VM = New Vue ({});
2, instantiate VUE Need to pass a parameter (option object);

3, parameter: Option object can be included, data (DATA), Mount Element (EL), Method (Methods), Template, Lifecycle Function, etc.;

4, extended constructor VUE to create a reused component constructor with a predefined option, all components are extensioned instances, using Vue.extend (}) To expand;

Note: Although the extended instance can be created, it is recommended to register with a custom element in most cases, and then declare in the template.

When you create an Vue instance, you can pass an option object. This tutorial is mainly described how to use these options to create the behavior you want. As a reference, you can also browse the full option list in the API document.

A Vue application consists of a root Vue instance created by New Vue, as well as an optional nested, multiplexed component tree. For example, a TODO application component tree can be like this:

root instance └─ Todolist├─ TodoItem│ ├─ deletetodobutton│ └─ EditOdobutton ─ TodolistFooter├ ─ CleartodosButton └─ TodolistStatistics

We will be in a later component system The chapter is specifically expanded. However, now you only need to understand that all VUE components are Vue instances and accept the same option object (except for some options unique to some root instance).
 1.2, Data and Method   When an Vue instance is created, it adds all the properties that can be found in the Data object to the Vue's response system. When the value of these attributes changes, the view will generate "response", that is, match updates to a new value. 
// Our data object var data = {a: 1} // This object is added to a VUE instance VAR VM = New Vue ({Data: DATA }) // They reference the same object! VM.A === DATA.A / / => true // Setting properties will also affect the original data VM.A = 2DATA.A / / => 2 // … vice versa DATA.A = 3VM. A / / => 3

When these data changes, the view will rendering. It is worth noting that only the attributes present in the DATA are responding when the instance is created. That is to say, if you add a new attribute, like:

VM.B = ‘hi’

  Then the change to B will not trigger any view of any view.  Example

VUE2 example
   

VAR DATA = {A: 1} // Example VAR VM = New Vue ({EL: “# App1″, DATA: DATA, Updated: function () {console.log (” The instance is updated! “);}});

Result:
     If you know that you will need a property later, but when it is empty or does not exist, then you only need to set some initial values. For example:    Data: {NewTodotext: ', Visitcount: 0, HidecompletedTodos: False, Todos: [], Error: null}   
In addition to the Data property, the Vue instance exposes some useful instance properties and methods. They all have a prefix to distinguish from user-defined attributes. For example: VAR DATA = {a: 1} var VM = New Vue ({EL: '# example', DATA: DATA}) VM. $ Data == = DATA / / => Truevm. $ EL === Document.getElementByid ('example') // => true // $ watch is an instance method VM.$ Watch ('a', function (newvalue, oldvalue) {// This callback will be called after `VM.A` to call})
In the future, you can Refer to the full instance properties and methods of the API.

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Explanation
   VM._UID // The self-increasing IDVM._ISVUE / / label is a VUE object to avoid being used by the OBServeVM._RenderProxy // Proxy agent object VM._self // Current VM instance VM. $ Parent // In custom subcomponents, Pointing an instance VM. $ Root // pointing to root VM instance VM. $ Children // Current component of the sub-component instance of the current component VM. $ REFS VM._WATCHER = NULLVM._INACTIVE = FALSEVM._IMOUNACTIVE = FALSEVM._IMOUNTED = FALSE / / Identifies if the VM._ISDESTROYED = FALSE // Identifies whether the VM._ISBeingDestroyed = false // Identifies whether the custom event of the VM._Events // current element is destroyed VM._HASHOKEVENT / / markup Hook: The event VM. $ vnode // The current custom component is vnode in the parent component, equivalent to VM. $ Options._parentVNodeVm._vnode // Current component's vnodevm._staticTRees // Analysis of the current component template The render function array VM. $ EL // The root corresponding to the current componentElement VM. $ Slots // Defines slots in the parent component, is an object button for an array VM. $ Scopedslots = EmptyObject // The internal render function is used to create vm._c = (A, B, C, D) => CreateElement (VM, A, B, C, D, FALSE) // User Custom Render method, incoming parameter Vm. $ CREATEEELEMENT = (A, B, C, D) = > CreateElement (VM, A, B, C, D, TRUE) VM._Props // is created by Observe's storage PROPS data object VM._Data // Object VM._ComputeDwatChers // saved by Observe's storage data data. Watcher object 

  1.5, example parameter VM. $ Options  
VM. $ OPTIONS
Actually, we

New Vue (options) Options

This option object can be incorporated attribute

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

DECLE TYPE ComponentOptions = {// Data Data: Object | Function | Void; // Introduction DATA Data Props ?: {[Key: String]: propOptions}; // PROPS Inferred Data PropsData ?:? Object; / / For custom components, the parent passed the calculation attribute of the data computed ?: {// incoming computation at the `PrOPS` (Key: StriNg]: function | {get ?: function; set ?: function; cache ?: boolean}}; methods ?: {[key: string]: function}; // incoming method Watch ?: {[key: string ]: Function | String}; // Introduced Watch // Dom EL ?: string | Element; // Introduced EL String Template ?: String; // Introduced Template RENDER: (H: ( ) => Vnode) => vNode; // Incompile RENDERRR ?: (h: () => vnode, err: error) => vnode; staticRenderfns ?: array

vnode>; // hook function beforeCreate ?: Function; created ?: Function; beforeMount ?: Function; mounted ?: Function; beforeUpdate ?: Function; updated ?: Function; activated ?: Function; deactivated ?: Function; beforeDestroy ?: Function; destroyed ?: Function; // assets directives ?: {[key: string]: object}; // instructions ?: {[key: string]: class Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解}; // subcomponent definition transitions ?: {[key: string] : ObjecT}; filter {[key: string]: function}; // filter // context provides ?: {[key: string | symbol]: any} | () => {[key: string | Symbol] : any}; inject ?: {[key: string]: string | symbol} | array

; // COMPONENT V-model CUSTOMIZATION MODEL ?: {Prop ?: string; Event ?: string;}; // misc Parent ?: Component; // Parent component instance Mixins ?: Array

; // Mixins Inferred Data Name ?: string; // Current Component name EXTENDS ?: Class

| Object; // Extends Data DELIMITERS ?: [String, String]; // Template Separator // Private Attributes When the internal creation of custom components, use _iscomponent ?: true; // Is it a component _propkeys ?: array
12 / s 传 传 对入 _ _ 当 对 组 对 当 对 组 对 组 对 对 对 组 对 组 对 组 对 组 对 事 事 组 事 事 事 事 事 事 事 事 事 事 的 事 事 事 对 事 对_RenderChildren ?:? Array ; // Define the vNode array of child elements within the current element in the parent component _ComponentTag:? string; // Custom label name _ScopeID:? string; _baSE: Class
; // vue _parentelm:? node; // The parent DOM node of the current custom component _refelm:? node; // Current element's nextslibing element, that is, the current DOM is inserted into _parentelm knot Pre-point _}}   
1.5.1, computed calculation attribute
The binding expression in the template is very convenient, but they actually Only for simple operations. Put too much logic in the template will make the template too heavy and difficult to maintain. For example:

{msg.split (”). Reverse (). Join (‘)}} Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Use the calculation attribute to define a method to be reused and the template will be more simple:

       {{msg.split (''). Reverse (). Join ('')}}    {{REVMSG}}  
VAR APP1 = New Vue ({EL: “# app1” , DATA: {MSG: “Hello”}, computed: {revmsg: function () {return this.msg.split (”). Reverse (). Join (”);}}};
[ 1

Results:

  Note:    1, the method defined in compute only allows for attributes, cannot with parameters, which limits its reuse. 
2, the method will re-call
3 when the attribute in the method changes, and the arrow function should not be used to define the calculation attribute function

4, the computed calculation attribute can be Cache the attribute, the calculation attribute is only recalculated when the attribute changes when the property changes, if an attribute does not complete the required function, it can be considered to calculate
1.5 .2, WATCH computing attribute
  An object, the key is an expression that needs to be observed, and the value is the corresponding callback function. Value can also be a method name, or an object containing options. The Vue instance will call $ Watch () and traverse every property of the Watch object during instantiation.        VUE2 example  

{A}} B:

{{b}}

C: {{cxyz}} D: { {D}}

{{cxyn}} VAR APP1 = New Vue ({EL: "# app1 ", DATA: {A: 1, B: 2, C: {x: {y: {z: 3,N: 3}}}, d: 4}, watch: {a: function (val, oldval) {Console.log ('a new:% 5s, original:% 5s', val, oldval);}, // Method Name B: 'Watchb', // Object, Depth Monitor C: {Handler: Function (Val, OldVal) {Console.log ('C New:% 5S, Original:% 5S', JSON.STRINGY (VAL), Json.Stringify (OldVal));}, Deep: true}, // Monitor D: {Handler: Function (VAL, OldVal) {Console.log ('C New:% 5s, Original:% 5S', VAL, OldVal);}, immediate: true // Setting the initial value will also call}}}}, methods: {Watchb: function (Val, OldVal) {Console.log ('B N new:% 5s, the original:% 5s', VAL ,}}}); var watchb = function (val, oldval) {console.log ('B new:% 5s, original:% 5s', val, oldval);}

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Note: The arrow function should not be used to define the Watcher function, and the object type is not deep. Copy, just quoted.

1.5.3, Method Methods

Methods will be mixed into the Vue instance. These methods can be accessed directly through the VM instance, or in the instruction expression. The THIS in the method is automatically bound to the Vue instance.

VAR VM = New Vue ({data: {a: 1}, methods: {plus: function () {this.a ++}}}) VM.PLUS ) VM.A // 2

  {{msg}}      VAR APP1 = New Vue ({EL: "# app1", data: {msg: "vue"}, methods: {add: function (str) {return this.msg + = Str;}}}); console.log (app1.add (3));    



Note that the arrow function should not be used to define Method Function (for example, Plus: () => this.a ++). The reason is that the arrow function binds the context of the parent's scope, so this will not point to the Vue instance according to the expectations, this.a will be undefined.
1.5.4, small knot
Computed is calculated, Methods is the calculation method, the most important difference is that the compute calculation property can cache

attribute, the calculation property is only recalculated when the attribute changes, as long as it is The value has not changed, it does not render, but the Methods method is different. When the method is called each time, it will be re-executed. 1, the instance of each Vue agent all attributes in its Data object, the agent's attribute is responding;

2, add new attributes to the instance if the instance is created Do not trigger a view update; 3, do not use the arrow function or in the instance or callback function (such as VM. $ Watch ('a', newval => this.mymethod ())) uses an arrow function. Because the arrow function binds the parent context, this is not as the VUE instance as expected, but this.mymethod is not defined. 4, the Vue instance exposes some useful instance properties and methods with prefix $ facilitating DATA distinguishing between A, VM. $ EL: Type (htmlelement) mount element , The DOM root element of the Vue instance;
B, VM. $ DATA: Type (Object), Vue instance observed data object
C, VM. $ PROPS: Type (Object), Properties

D, VM. $ OPTIONS: Type (Object), is useful for the current Vue instance, which is useful when you need to include custom properties in the option.

E, VM. $ PARENT: Type (Vue Instance), Father Instance.

F, VM. $ Root: Type (Vue Instance), the root Vue instance of the current component tree, if there is no parent instance, is the instance itself. Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解 H, VM. $ Children: Type (Array (Vue Instance)), current instance direct sub-component

Note $ Children does not guarantee order, nor responsive. If you find that you are trying to use $ Children to make data binding, consider using an array to generate a sub-assembly with V-FOR, and use Array as a true source.

i, VM. $ Slots: Type ({[Name: String]:? Array

}), use to access the content distributed by SLOT. Each name Slot has its corresponding attribute (for example, the content in slot = “foo” will be found in VM. $ Slots.foo). The Default property includes all nodes that are not included in the name of Slot.

K, VM. $ REFS: Type (Object), an object, which contains all subcomponents with REF registration;

L, VM. $ Isserver: Type (Boolean), The current VUE instance is running on the server;
Official website corresponds to
  1.5.5, arrow function  
arrow function is an eS6 introduced by an syntax, making the write function easier Similar to the lambda expression, the basic format is as follows:

Example:

          
VAR m1 = a => a + 1; console.log (M1 (100)); // Similar to VAR M2 = Function (a) {RETURN A + 1;} console.log (M2 (100)); var M3 = (a, b) => a + b; console.log (M3 (100, 200)) ; VAR M4 = (a, b) => {a ++; b ++; return A + b;}; // If there are multiple expressions in the method body, a large bracket is required to return Console.log (M4 (100,200));
Second, life cycle 2.1, instance life cycle
Each Vue instance has to pass a series of initialization processes before being created. For example, you need to set data listening, compiling templates, mount instances to DOM, update DOM when data changes. At the same time, there will be some functions called lifecycle hooks during this process, and give users a chance to add their own code in some specific scenarios.

, such as the Created hook can be used to execute code after an instance is created:

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

New Vue ({DATA: {a: 1}, create) Function () {// `This point to the VM instance console.log (‘a is:’ + this.a)}} // =>” a is: 1 “

There are also some other hooks, calls under different scenarios of the instance life cycle, such as mounted, updated, destroyed. The this of the hook pointing to the Vue instance calling it.

Do not use arrow functions on option properties or callbacks, such as Created: () => Console.log (this.a) or Vm. $ Watch (‘a’, newvalue => this.mymethod () ). Because the arrow function is binding with the parent context, this is not as the Vue instance you expect, often causes uncaught typeerror: CannoTREAD PROPERTY OF Undefined or Uncaught TypeError: this.mymethod is not a function.

2.2, lifecycle

The figure below illustrates the life cycle of the instance. You don’t need to make up the horse to understand all things, but with your constant learning and use, its reference value will get higher and higher.

1. BeforeCreate

After the instance is initialized, data observation ( Data Observer) and Event / Watcher event configuration before being called.

2. Created

The instance is called after the completion is created. In this step, the instance has completed the following configuration: Data Observer, the attributes, the operation, Watch / EVENT event callback. However, the mounting phase has not yet begun, and the $ EL attribute is currently invisible. Data can be requested during this period of the component. If the Keep-Alive component is cached, the lifecycle will not trigger again. If you need to update the data can change the current Router, if Router is the Router of the current component, request data.

Methods: {GetData: Function (ID) {… this.content = ‘test’;}}, created: function () {this.getdata (this .id);} … Watch: {$ route: function () {i (this. $ route.name == ‘xxx’) {this.getdata (this.id);}}}

3. Beforemount

Call before the mount: The associated render function is first called.

4. MOUNTED

VM. $ EL is mounted in the document, and the operation of the existing DOM node can be performed during this.

5. BeforeUpdate

The data is called, which occurs before the virtual DOM rendering and patch.

The state can be further changed in this hook, which does not trigger an additional rendering process.

6.Updated

The hook will be called after the virtual DOM rendering and patch caused by data changes.

When this hook is called, the component DOM has been updated, so you can now execute the DOM operation. However, in most cases, you should avoid changing the status during this because this may result in an unlimited loop.

7.Activated

When the Keep-Alive component is activated.

8.Deactivated

Keep-Alive component is called.
9.BeForedestroy
 The instance is called before it is destroyed. In this step, the instance is still available.  10.DESTROYED   Vue instance is destroyed. After the call, all things indicated by the Vue instance will be built, and all event listeners will be removed, and all sub-instances are also destroyed.  2.3, lifecycle example 1      
Vue2 Life Cycle

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

// Formatted Output Console.log (“Example:% C% S”, “Background: RED; Color: #fff “,” Vue2 Life Cycle “,” Start “); VAR App1 = New Vue ({EL:” # App1 “, DATA: {MSG:” Vue “}, before process: function () {Console. LOG (“Before:” + this.msg);}, create: function () {console.log (“After Creation:” + this.msg + “,” + this. $ el);}, beforemount: function ) {Console.log (“Mount:”); console.log (this. $ EL);}, mounted: function () {console.log (“After mount:”); console.log (this. $ EL);}, beforeupdate: function () {console.log (“instance update:”); console.log (this.msg); console.log (this. $ EL);}, updated: function () {Console.log (“instance update:”); console.log (this.msg); console.log (this. $ EL);}, beforeDestroy: function () {console.log (“instance destruction:” Console.log (this.msg);}, deStroyed: function () {console.log (“instance destroy:”); console.log (this.msg);}}); function design () {app1. $ destroy ();}

Initialization Result 1:

The result of modifying the value of the MSG is Vue2:

   
2.4, lifecycle example 2
Example 2:

VUE2 life cycle

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解 {Message}}

VAR App = New Vue ({EL: ‘#App’, Data: {Message: “South It College!”}, Beforecrible: function () {console.group (‘BeforeCreate creation pre-status == ============== “); console.log (“% C% S “,” Color: Red “,” EL: “+ THIS. $ EL); // undefined console. LOG (“% C% S”, “color: red”, “data:” + this. $ data); // undefined console.log (“% C% S”, “Color: Red”, “MessaGE: “+ this.Message)}}, created: function () {console.group (‘created creation is complete) ================”); console.log (“% C% S “,” Color: Red “,” EL: “+ this. $ EL); // Undefined Console.log (“% C% S “,” Color: Red “,” DATA: “+ THIS. $ Data); // has been initialized console.log (“% C% S”, “color: red”, “Message:” + this.Message); // has been initialized}, beforemount: function () {console. GROUP (‘Beforemount Mount Status ================ “); Console.log (“% C% S “,” Color: RED “,” EL: “+ ( THIS. $ EL); // has been initialized console.log (this. $ EL); console.log (“% C% S”, “Color: Red”, “DATA:” + this. $ data); // has been initialized Console.log (“% C% S”, “color: red”, “Message:” + this.Message); // has been initialized}, mounted: function () {console.group (‘ MOUNTED mount end status =============== “); console.log (“% C% S “,” Color: Red “,” EL: “+ this. $ EL ); // has been initialized Console.log(This. $ EL); console.log (“% C% S”, “color: red”, “data:” + this. $ data); // has been initialized console.log (“% C% S” “Color: Red”, “Message:” + this.Message); // has been initialized}, beforeupdate: function () {console.group (‘beforeupdate update pre-status =========== ==== “); console.log (“% C% S “,” Color: Red “,” EL: “+ this. $ EL); console.log (this. $ EL); console.log “% C% S”, “Color: Red”, “Data:” + this. $ data); console.log (“% C% S”, “Color: Red”, “Message:” + this.Message) }, updated: function () {console.group (‘updated update completion status ================ “); console.log (“% C% S “,” Color : Red “,” EL: “+ this. $ EL); console.log (this. $ EL); console.log (“% C% S “,” color: red “,” data: “+ this. $ Data); console.log (“% c% s”, “color: red”, “message:” + this.Message);}, before.group (‘BEFOradStroy destroyed before the state =============== “); console.log (“% C% S “,” Color: Red “,” EL: “+ this. $ EL) Console.log (this. $ EL); console.log (“% c% s”, “color: red”, “data:” + this. $ data); console.log (“% c% s”, “Color: Red”, “Message:” + this.Message);}, destroyed: function () {console.group (‘destroyed destruction completion status =============== “‘ ); console.log (“% C% S”, “Color: Red”, “EL:” + this. $ EL; console.log (this. $ EL); console.log (“% c% s” “Color: Red”, “Data:” + this. $ data); console.log (“% C% S”, “color: red”, “Message:” + this.Message)}

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Initialization results:

Update Message Value:
   

2.5, manual mounting and calling event 2.5.1, manual mount

VM. $ Mount ([ElementorsElector])

If the Vue instance does not receive the EL when instantiatedOptions, it is in the “unmischad” state, and there is no associated DOM element. You can use VM. $ Mount () manually mount an unmounted instance.

If the ElementorsElector parameter is not provided, the template will be rendered as an element outside the document, and you must insert it into the document using the native DOM API.

This method returns an instance itself, so that other instance methods can be called chain.

Var mycomponent = Vue.extend ({Template: ‘

Hello!

‘} // creates and mounted to #app (will replace # App) new mycomponent (). $ mount (‘# app’) // 同 同 NEW MyComponent ({EL: ‘#app’}) // or rendered outside the document and then mount Var Component = new mycomponent () . $ Mount () document.getlementByid (‘app’). Appendchild (Component. $ EL)

Example:

VUE2 Life Cycle

# app1 {color: red;} # app2 {color: blue;}

Manual mount 1

Manual mount 2

VAR APP1 = New Vue ({ Template: “

{{msg}}

“, DATA: {MSG:” Hello Vue2! “}}; function loadData1 () {app1. $ mount (” # app1 “); document.getlementByid (” app1 “). appendchild App1. $ EL);} Function loadData2 () {app1. $ mount (); document.getlementByid (“app2”). Appendchild (app1. $ el);}

     2.5.2, destruction example   VM. $ Destroy () completely destroyed an instance Clean it with other instances, unfold all of its instructions and event listeners.   2.5.3, forced update  
VM. $ ForceUpdate () forces the Vue instance to re-renown. Note that it only affects the instance itself and the subcomponents inserted into the slot content, not all subcomponents.
Single Page Web Application, SPA, is only one web page application, which is a web application that loads a single HTML page and dynamically updates the page when the user is interactive with the application. Provides an official command line tool to quickly build large single-page applications (SPA). This tool provides a built-in build configuration for modern front-end development workflows. Just take a few minutes. Projects that can be created and started with a thermal overload, saving, and built-in build configurations available for production environment:
# Global Install Vue-CLI $ NPM Install - Global Vue-CLI # Create a new project based on WebPack Template $ Vue Init Webpack My-Project # installation dependence, take you $ cd my- Project $ NPM Install $ NPM RUN DEV
Note: The CLI tool assumes that the user has a certain degree of understanding of Node.js and related buildings. If you are a newbie, we strongly recommend reading the guidelines without building a tool, using the CLI after familiar with the Vue itself.

3.1, the environment is built 3.1.1, install node.js

Download and install Node from N Ode.js, the installation process is very simple, all the way “Next” is ok. After the installation is complete, open the command line tool (WIN + R, then enter CMD), enter Node -V, as shown below, if the corresponding version number appears, the installation is successful. Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

If the installation is unsuccessful, you can directly modify the installation package into a compressed package, and then configure the environment variable after decompression, it will become a green version.

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Here, in the official website, after the official website download and install node.js, it has come with NPM (package management tool), but also pay attention to NPM version It is best to 3. xx or more to avoid the following effects.

Note that the version cannot be too low, if you have installed the low version of Node, you can use NPM to directly update. Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解 3.1.2, modify npm is Taobao mirror

Because NPM’s warehouse has many abroad, the speed is slow, it is recommended to modify CNPM and replace it with Taobao mirror.

Open the command line tool, copy the following configuration:

  NPM install -g cnpm --registry = https: //registry.npm.taobao.org   Installation here is because we use npm servers to be foreign, some When we installed "dependencies" very slowly and slowly, so using this cnpm to install "dependence" we need to say. After the installation is complete, enter cnpm -v, as shown below, if the corresponding version number appears, the installation is successful.      
3.1.3, Install WebPack
Install WebPack, open the command Tool input: NPM INSTALL WebPack -G

installation is completed After the

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

As shown below, if the corresponding version number is present, the installation is successful.

3.1.4, Installing Vue-CLI Scaff Engineering Tools Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Open Command Line Tools Enter:

CNPM Install Vue-Cli -g

After the installation is complete, input Vue -V (Note that the “V” of the uppercase), as shown below, if corresponding The version number, the installation is successful.

3.2, build items
1), find a file clip on the hard disk. There are two ways to specify to the relevant directory:
  1CD directory path 
2 If you install git, right click on the relevant directory to select Git Bash Here
2), install the Vue Scaffolding: Vue Init Webpack ProjectName, note that “Projectname” is the name of the project It is said that it is a casual name, but “can’t use Chinese.” Tips Select Item:

$ Vue Init Webpack ExpRice ——————– – This is the command that installs the Vue Scaffolded this Will Install Vue 2.x Version of The Template. ——————- Here you will create a Vue 2. X version of the project for Vue 1.x Use: Vue Init Webpack # 1.0 ExpRice? Project name (exprice) ——————- Project Name? Project Name Exprice Project Description (a Vue.js Project) ——————– Project Description? Project Description a Vue.js Project? Author Datura —— ————— Project creator? Author datura? Vue Build (Use arrow keys)? Vue Build Standalone? INSTALL VUE-ROUTER? (Y / N) —— ————— Whether to install the Vue route, that is, the SPA (but the module required for page application)? Install Vue-router? Yes? USEESLINT TO LINT YOUR CODE? (Y / N) N ——————– Whether Eslint detection rules are enabled, here personal suggestion No? Use eslint to lint Your Code? NO? SETUP UNIT TESTS WITH KARMA + MOCHA? (Y / N)? Setup Unit Tests with Karma + Mocha? YES? Setup E2E Tests WITH NightWatch? (Y / N)? Setup E2E Tests WITH NightWatch? Yesvue-CLI · Generated “exprice” .to get start: ——————— Here you explain how to start this service cd expricenpm installnpm run dev
      3), the CD command enters the created engineering directory, first CD ProjectName;   4), the installation item is dependent: NPM INSTALL, because the automatic build process There is already a package.json file existing, so you can install dependencies here. Do not install from domestic mirrors (will result in a lot of relying libraries behind), but if it is really installed, "a handle" is not successful, then use: cnpm install   5), install Vue routing Module Vue-Router and Network Request Module Vue-Resource, Enter: CNPM Install Vue-Router Vue-Resource --save.   
3.3, running items 6), start the project, enter: NPM Run DEV. After the service starts successfully, the browser will open a "welcome page" by default, as shown below:

After the compilation is successful, you can view items directly in the browser:
3.4, Vue-CLI HelloWorld
Understand the default template content, we can start defining your own Vue program, here writing a simple helloworld, in the src directory Create a Hi.Vue file, the content is as follows:

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

{{msg}}

Export Default {Name: ‘Hi’, Data () {Return {MSG: ‘My First Vue-CLI App!’}}, Methods: {Sayhi: Function () {Alert THIS.MSG);}}}

# app1 {font-family: “Microsoft Yahei”; Color: DODGERBLUE; FONT-SIZE: 20PX;}

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

Modify MAIn.js

///////////////////////////////////////////////////////////////////////////> With an alias.import vue from ‘Vue’Vue.config.ProductionTIP = FALSE / * ESLINT-DISABLE NO-New * / New Vue ({EL:’ #App ‘, Template:’

‘, Components: {App}})

   
Fourth, Example Download
https://git.coding.net/zhangguo5/Vue2.git

Videos

https: // Www.bilibili.com/video/av17503637/

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

6. Job

1. Please define any Vue instance to trigger eight events in the Vue instance, The result is output to the console, requiring data initialization and mounting. Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解 2, use Vue2 + BootStrap to complete the following function:

Requirements the addition function

b), implement the delete function

c), realize editing, increase button

d), realize interlaced

E),Distortment

   

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解 Summary

The above is the example of the Vue introduced to everyone, the life cycle is detailed with the Vue Scaffold (Vue-CLI) instance, I hope to everyone Help, if you have any questions, please leave a message, Xiaobian will reply to everyone in time. Thank you very much for your support of Tumi Cloud Website!

Vue的实例、生命周期与Vue脚手架(vue-cli)实例详解

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment