Vuejs basic knowledge and project summary

Source: Internet
Author: User
Tags emit event listener

1, Build:dev-server.js is executed when the terminal command is started, it can modify the port number (modify the 16th line)

2, index.html is the entire file entrance

SRC is the file you wrote.
3, Main.js is the main logical entrance of the current file

App.vue is the root component

4. Some events and methods

v-on:click= "Event name"
v-on:keyup= "event name"//trigger when any key is pressed
V-on:keyup.enter= "event name"//triggered when the ENTER key is pressed
V-on:keyup.alt.enter= "event name"//need to hold down the ALT key and press ENTER to be called

More events can go to official documents to view

5.
<li v-for= "User in Users" >
<input type= "checkbox" class= "Toggle"
V-model= "User.contacted"
>
<!--the following span: class is bound to a style, user.contacted is true when there is this style, false when there is no this style--
<span:class= "{contacted:user.contacted}" >
{{User.name}}:{{user.email}}
<button v-on:click= "deleteuser (user)" >x</button>
</span>

</li>

6. How to use Routing

Modified the Main.js
Import vue from ' Vue '
Import vuerouter from ' Vue-router '
Import App from './app '
Import Users from './components/users '
Import Test from './components/test '

Vue.use (Vuerouter)

Vue.config.productionTip = False
Set up routes
Const ROUTER = new Vuerouter ({
Mode: ' History ',
Base:__dirname,
routes:[
{path: "/", component:users},
{path: "/test", component:test},
]
})
/* eslint-disable No-new */
New Vue ({
Router
Template: '
<div id= "App" >
<ul>
<li>
<router-link to= "/" >Users</router-link>
<router-link to= "/test" >Test</router-link>
</li>
</ul>
<router-view></router-view>
</div>
`
}). $mount ("#app")

7. How to use HTTP requests

Installing resource NPM Install Vue-resource--save

There are some well-written data in jsonplaceholder.typicode.com

Created method does not need to invoke automatic execution


8. Core concept

Vue: Modular bidirectional Data Flow (based on DefineProperty in ES5), ie9+ support

Angular: Modular bidirectional data binding (Dirty detection: An array ($watch))

There is a comparison between Vue and other frames on the Vue website (it is recommended to read Vue again)


Bidirectional Data Flow:
1 Direction: JS Memory property changes, affecting the page changes

1-Way: page changes affect JS Memory property changes


9. Common Directives

V-text is an element innertext can only be used in a double label

V-html is an element's innerHTML and cannot contain {{XXX}}

Whether the v-if element was removed or inserted

Whether the v-show element is displayed or hidden

V-model bidirectional Data binding

V-bind:value: Assigning value v-bind is one-way data binding (Memory JS change impact page)

Create a project basic steps:

1. Create index.html

Create div tags, id= "App"

2, Configuration Main.js

1) Introducing Vue
2) Introduce App.vue, use its contents to replace div id = app
3) Building Vue instances

New Vue ({

Destination of rendered content

El: ' #app ',

Render Content

Render:function (c) {//C is just a formal parameter and can be called anything
return C (APP)

}

})

In general, the key is fixed, and the value is the one you set (variable)

3, App.vue

Inside can write code in the browser to display the

<template></template>
<script></script>
<style></style>


10, class combined with v-bind use

To assign a value to a class based on the result of a mutable expression, you need to use the v-bind:class= "XXX"
V-bind: Property name = "Expression", the result of the end expression operation is assigned to the property name

--The simplified notation is: ': property name = ' expression '
Class: Classification of results:
--A style: Returns a string (ternary expression and a list object of key and style)
--Multiple styles: Return object (Style does key,true or false value)

Arrow function: (c) =>{return C (APP)}

1, the parameter is a time, the parentheses can be omitted
2, the contemporary code only one row and is the return value, you can omit the curly braces
The above arrow functions are abbreviated as C = > C (App)

V-bind:class= "Isred?" Red ': ' green ' "ternary expression to take one and return a string

Take multiple to return an object


Complex situation, through traversal, according to the current object's score, match scores and styles
List object, use the result to do key, take the object's value, and finally return the string to do the style name
: class= "{' A ': ' Red ', ' B ': ' Green '}" [Stu.score]
Here Stu.score is the key, and the value of the object is taken by score.

11. Use of methods and v-on

* Methods for binding Events
' v-on event name = ' Expression | | Function name "' Example: v-on:click=" Change () "
Shorthand: ' @ event name = ' Expression | | Function name "'

* Function Name If there is no argument, you can omit () give only one function name, such as v-on:click= "Change"

* Declare the function within the component, the root property of the export default object plus the Methods property, which is an object,

--key is the function name, the value is the function body
* In export default this object's root property plus the Data property, which is a function that returns an object
--The object's property is the name of the variable we initialized

* If you use variables or functions in the template, you do not need to add this, you need to add this to the script.

12, the use of v-for

* Operation Array (ITEM,INDEX) can be used
* Operation Object (VALUE,KEY,INDEX) can be used
* Key is a property similar to Trank by
* In order to tell Vue, JS elements, and the link between the page, when attempting to delete the element, is the deletion of a single element instead of the full version of the replacement, so need to correlate its relationship, set (must, performance) 2.xxx must be set after


13. Beautiful List

* Bind class, show different classes according to grade level
: class= "{' A ': ' Red ', ' B ': ' Green ', ' C ': ' Blue ', ' D ': ' Pink ', ' E ': ' Gray '}[hero.score]"

* Add and remove functions for list
Add: Push object to array by clicking Event
Delete: According to index in V-for, one of the clicked strips will be deleted.


14. Parent-Child Components

The style in the Vue file is filled in by default, and if you want to work locally, add scoped to the style label

* Father and son, use the father, the child is used
* The parent needs to declare subcomponents, introduce child component objects, and declare them as follows
"' JavaScript
Import Component Object from './xxx.vue '
Export default{
components:{
Component Name: Child Component Object
}
}
* Global components, more convenient to use, no need to declare, directly with
* Introduced once in main.js, using ' vue.component (' Component name ', ' Component object ') '
* All components can be used directly from the component name
Vue.component (' Headervue ', headervue);//Register a component, the first parameter is the name, the second argument is the actual object
(Show what, what features)

15. The parent component passes the value to the child component

* The parent component passes the value through the properties of the child component
--There are 2: constants: prop1= "Constant Value"
Variable: prop2= "variable name"
Child components need to be declared
-Root attribute props:[' Prop1 ', ' PROP2 ']
-use {{PROP1}} directly in the page
-How should I use Prop1 in JS? Get through THIS.PROP1

16. Sub-component Communication (Vuebus) extension to Parent component

$on (' event name ', FN (PROP1,PROP2)) by an object such as New Vue ()
Another component introduces the same vuebus to $emit (' event name ', PROP1,PROP2)

Create a JS file for the communication, code for
Import vue from ' Vue ';
var connector = new Vue ();
Export default connector;

The template part code in the parent component:
<sub-vue></sub-vue>
<button @click = "Listen" > Dad anxiously listening to the phone </button>

Part of the code in script:

Import connect from './connector.js ';
methods:{
Listen () {
Connect. $on (' phone ', function (msg) {
Console.log (msg);
})
}
}
The template part code in the subassembly:
<button @click = "Calldaddy" > Call Papa </button>

Part of the code in script:
methods:{
Calldaddy () {
Transmit signal
Connect. $emit (' phone ', ' 62 minutes ')
}
}

17. Vue.js Document Classification
1, the overall representative of Vue.
2. The instance represents this. or new Vue ().
3. The options represent the parameters of the new Vue () or the properties inside the export default
Global: Invoke sub-API and configuration via Vue

Global configuration
Silent
Optionmergestrategies
Devtools
ErrorHandler
Warnhandler
Ignoredelements
Keycodes
Performance
Productiontip

Global API
Vue.extend
Vue.nexttick
Vue.set
Vue.delete
Vue.directive
Vue.filter
Vue.component
Vue.use
Vue.mixin
Vue.compile
Vue.version

Options/Data options/category
Data
Props
Propsdata
Computed
Methods
Watch
Option/DOM Options
El
Template
Render
Rendererror
Option/Resource Options
Directives
Filters
Components

The above band options are related to the instance, such as:

New Vue ({
El
Render
})
Export default{
components:{},
methods:{

}
}

Example: This and new Vue () within the component

Instance Methods/Events
VMs. $on
VMs. $once Trigger only once
VMs. $off canceling an event
VMs. $emit

Instructions
V-text
V-html
V-show
V-if
V-else
V-else-if
V-for
V-on
V-bind
V-model
V-pre
V-cloak
V-once

18. Review

* Vue Single file mode Xxx.vue
* 1: Ready configuration file Package.json (Package Profile && Package command npm run dev) +webpack.config.js file (packaged configuration file)
* 2: Create index.html (page of single page app)
* 3: Create main.js (entry file)
* 4: Introduction of Vue and related files Xxx.vue
*5:new Vue (Options)
*6:options:
-data
-methods
-components (Group declaration sub-component)
-props
* 7: Example
-Within the component (Xxx.vue) the This
-new Vue ()
-Event
+this. $on (event name, callback function (parameter))
+this. $emit (event name, data)
+this. $once (event name, callback function (parameter)) is triggered once
+this. $off (event name); Cancel Event
* 8: Global
-vue.component (' Component name ', Component object) can be used anywhere

* 9: Component Transfer value
-Parent Child: attribute as parameter
+ constant title= ' xxx ' sub-component declaration receive parameter props:[' xxx ']
+ variable v-bind:title= ' num ' sub-component declaration receive parameter props:[' xxx ']
-Sub-parent: Vuebus (only the same car, that is, the same event name)
+ Stop to Parent component first, on
+ Drive to sub-assembly, if necessary, emit, trigger the callback function of the above time


19. Filter

*content | Filters, no relevant built-in filters are available in Vue, customizable filters
* Filter within the component + global filter

-In-component filters are a filters attribute (an object) + multiple keys are different filter names, and multiple value is the filter function body corresponding to key

-Global filter is Vue.filter (name, FN)

* Enter the content to help me make a reversal
When the filter in the global filter and the component is called in, the filter in the component is valid

Summarize:
-Global: Large range, if the same name occurs, the rights are small
-Within the component: If the same name is present, the power is large and the range is small

20. Get DOM Elements

* Straws, the front-end frame is to reduce DOM operation, but in certain cases, also left the back door.
* on the specified element, add ref = ' name '
* Add this $refs where it is obtained. Name a
-if ref is placed on a native DOM element, the data obtained is the native DOM object
+ can be operated directly
-if ref is placed on a Component object, it gets the component object and operates
-The corresponding event
+created the initialization of the data, the DOM is not generated at this time, and the DOM cannot be manipulated
+mounted the data has been loaded onto the DOM, you can manipulate the DOM

* Two hook functions created and mounted (can also be called events)
After the component is created, the data is initialized, but the DOM has not yet generated
Created () {//event handler function (created)
Console.log (' Created: ', this. $refs. mydiv);//Cannot get
},
After the data is loaded into the DOM, various data are in place, rendering the data to the DOM, the DOM has been generated
Mounted () {
Console.log (this);
Console.log (' Sub: ', this. $refs. Sub. $el);
Gets the component object, and gets the DOM object to its
this. $refs. Sub. $el. InnerHTML = "Hello";
Console.log (' mounted ', this. $refs. mydiv);
Operations involving the DOM class
this. $refs. mydiv.innerhtml= "123456789"
Operations that involve data
This.text= "laughing and joking";
}

21, Mint-ui

* Hungry, Element-ui used on the PC side
* Mobile side version Mint-ui
*https://mint-ui.github.io/#!/zh-cn
Install mint-ui command: NPM i mint-ui-s

Note: The project should be introduced as needed

Introducing All components
Import vue from ' Vue ';
Import Mint from ' Mint-ui ';
Vue.use (Mint);

Introduce some components on demand
Import {cell,checklist} from ' Minu-ui ';
Vue.component (Cell.name,cell);
Vue.component (checklist.name,checklist);

META:VP Enter, you can come out Meta's complete adapter code:

<meta name= "viewport" content= "Width=device-width, User-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0 ">

Attention:
-If it is installed all the way
+ 1: The component tag + 2 can be used directly in the template: it must be declared in script, that is, the Component object is introduced (load on demand)

22, access to the website technology plug-in

* Wappalyzer
Get the technology to use for the current site

23, Vue-router

* The core of the front-end routing is the change of the anchor value, rendering different data for the specified DOM location according to different values

*ui-router: Anchor value change, how to get the template? Ajax

*vue, the template data is not the AJAX request, but rather the call function gets to the template content

* Core: Anchor point value change
* After you see the Vue start, you know you must vue.use
* Vue's core plugin:
-vue-router Routing
-VUEX managing global Shared data
* How to use
-1: Download ' npm i vue-router-s '
-2: Introduction of ' Import Vuerouter from ' Vue-router in Main.js
-3: Install plugin ' vue.use (vuerouter) '
-4: Create a Routing object and configure routing rules
+ ' let router = neew vuerouter ({routes:[{path: '/home ', Component:home} '}) '
-5: Pass its routing object to the instance of Vue, in options
+ options Add ' router:router '
-6: Leave a pit in the App.vue
<!--pit, very important--
<router-view></router-view>

24. Vue Learning Style

Vue: How did this object come from?
Use of the framework, follow the Vue code how to write, will not copy
Framework, first grasp the application

Parts of the component:

structure, style, dynamic effects

Compile-to-core based on Webpack, and ultimately understand the benefits of packaging

25, the naming method uses Router-link

Create a Route object and configure routing rules
Let router = new Vuerouter ({
routes:[
Objects
{name: ' Music ', Path: '/mymusic ', component:music},
{path: '/movie ', Component:movie}
]
})
*router-link actually find the corresponding path according to the name;
<!--1, where to go--
<router-link:to= "{name: ' Music '}" > Enter music 1</router-link>
<router-link:to= "{name: ' Music '}" > Enter music 2</router-link>
<router-link:to= "{name: ' Music '}" > Enter music 3</router-link>
<!--can also be used with paths, but not recommended
<router-link to= "/movie" > Go to Movies </router-link>
Vue.use (vuerouter);//Mount Properties

Second, basic learning

1. Data binding and view components in Vue response

Can find Vue's learning resources from GitHub
1: Progressive frame vue

What is Vue?

Build a progressive framework for the user interface
Focus on the view layer only

Two core points in 2:vue

Two core points in Vue
1: Data binding of the response

1) Automatically update view when data changes
2) Monitor the operation of the data using the Setter/getter proxy data in Object.definedproperty (incompatible IE8)

2: Combination of view components

1) UI page map to Component tree
2) partition components can be maintained, reusable, testable


3: Virtual DOM

The speed of running JS is very fast, a lot of operation Dom will be very slow often after updating the data will re-render the page caused by waste of resources.

4:MVVM mode

M:model Data Model
V:view View Model
Vm:view-model View Model

Classic example: (Here is the code to introduce vue.js)
<div id= "Demo" >
<input type= "text" v-model= "message"/>
<p>{{message}}</p>
</div>
Let data = {message: ' Hello,world '};
var vm = new Vue ({
El: ' #demo ',
Data:data
});

5:vue instances

*vue instances
Each application creates a root instance through the Vue constructor to start the new Vue (option object)
* Requires incoming Option object, object contains mount element, data, template, method, etc.
El: Mount element selector string| HtmlElement
Data: Proxy object| Function
Methods: Define Method Object

*vue Proxy Data

Each Vue instance proxies all the attributes in its data object, which are responded to by the proxied properties. The newly added property does not respond, and the view is not updated after the change.

* Vue instance self properties and methods
Expose your own properties and methods: Start with $, for example $el $data ....

6: Declarative Rendering

* Declarative: Just want to declare where to do what, without caring how to implement

* Imperative: The specific code needs to express where to do what, how to achieve
var arr = [1,2,3,4,5];
Find a multiple of each item in the array, and put it in another array
for (Var i=0;i<arr.length;i++) {
Newarr.push (arr*2);
}
var newArr = Arr.map (function () {});

*vue Declarative Rendering:
Arr.map (function (item) {
Return item*2
});

7: Instruction

What is an instruction?
is a special kind of custom inline property
The duty of an instruction is to apply certain behavior to the DOM when the value of its expression changes
In Vue, the instruction starts with V
8: Template
Two-way data binding in 9:vue

1) built-in instructions in Vue:
V-bind Dynamic binding data, abbreviated as:
V-on Binding Event Listener, abbreviated as @
V-text update data, overwriting an existing structure
V-html can parse the HTML structure in the data
V-show Toggle the Display property of an element based on true or false values
V-if Depending on the true value, the switching element will be destroyed, rebuilt
V-ELSE-IF Multi-condition judgment, rendering for true
V-else conditions are not consistent with rendering
V-for render elements or template blocks multiple times based on metadata
V-model creating two-way data binding on a form control element
V-pre skipping the compilation of elements and child elements
V-once is rendered only once, and subsequent data updates are not re-rendered
V-cloak hide the mustache syntax that is not compiled, set [Vcloak]{display:none} in CSS

2) HTML templates

Dom-based templates, which are parsed and valid HTML

Interpolated values:
Text: Using the "mustache" syntax, (double curly braces) {{value}}}
Function: Replaces the attribute value on the instance, and when the value changes, the interpolated content is automatically updated

Native HTML: Double curly braces output text that does not parse the HTML (if you want to parse HTML instead of text, you need to add v-html to the tag, v-html= "HTML" to remember that span cannot contain DIV)

Properties: Binding with V-bind to respond to changes

Using JavaScript expressions: Writing simple expressions

{{1+2}} {{ture?} "Yes": "No"}

3) Template string templates

Properties of the Template option object
The template will replace the mounted element. The contents of the mounted element are ignored
The root node can only have one (only one root node can be written in the template cannot have a parallel)
var vm = new Vue ({
El: ' #demo ',
Data:{abc:123},
Template: ' <div>{{abc}}<span>hello</span></div> '
})
Write the HTML structure in a pair of script tags, set type= "X-template"
The HTML of the template is written in script, such as:
<script type= "x-template" id= "temp" >
<DIV>{{ABC}}
<span>hello</span>
</div>
</script>
var vm = new Vue ({
El: ' #demo ',
Data:{abc:123},
Template: "#temp"
})

4) Template-render function

Properties of the Render options object
createelement (label signature, data object (can be omitted), child element)
binding class, value is an object, the object's key is the class name, value is an expression, Can determine whether true or false;
<div id= "demo";
<span:class= ' {red:addclass} ' ></span>
</div>
<style>
. red{
background-color:red;
}
. bg{
background:red
}
</style>
var obj = {
Addclass:true
}
var vm = new Vue ({
E L: ' #demo ',
Data:obj,
Render (creareelement) {
return creareelement (
"ul",//Label name
{
class:{
bg: True
},
style:{
fontSize: "50px"
},
attrs:{
ABC: "Hello"
}
},
[
creareelement ("Li" , 1),
creareelement ("Li", 2),
creareelement ("Li", 3),
]
)
}
})

The second parameter of the render function, the data object properties:
class:{}//Binding class, and ' V-bind:class ' API
style:{}//Binding style, and ' V-bind:style ' like API
attrs:{}//Add an inline property
domprops:{}//dom Element properties
on:{}//Bind event

nativeon:{}//Listen for native events
directives:{}//Custom directives
scopedslots:{}//slot Scope
slot:{},//define slot name
Key: "Key"//Add unique identifier to the element
Ref: "ref"//reference information

10: Translation API Address: https://tech.yandex.com/translate/

11: Command-line tool (CLI) for fast large-scale single-page applications

NPM Install--global VUE-CLI
Vue Init webpack My-project
CD My-project
NPM install loads the required modules
NPM Run Dev

12: Online Translation Project summary

1, build the project development environment
2. Creating Root Components and subcomponents
3. Introduce the Translateform component into the root component, refine this subassembly, see what the component includes, and then write the code. Wrap the code in the form, bind the event to the form, and commit the object in the form
4, need to get the input content, using the data method in the component, define a property, use this property through the method of V-model, bind the value to input.
5. Pass the value obtained above to the root component through this. $emit ("Method name (self-defined, such as Formsubmit)") (In fact, register an event)
This event is then bound in the Translateform tag in the root component, such as: <translateform v-on:formsubmit= "event name" ></translateForm>
If the event name is Translatetext, click the Translate button, you can call Tanslatetext this function. this. $emit ("Method name (self-defined, such as Formsubmit)", parameters that need to be passed (e.g. this.texttotranslate))
The parameter passed in the past needs to have a place to receive, namely in Tanslatetext this function to add the formal parameter.
6, the above to get the content you want to translate, need to translate, then need to rely on the translation API, the need to use the HTTP request call interface, using HTTP to install Vue-resource (because the author of Vuejs announced no longer maintain Vue-resource, and recommend that you use Axios).
After installation, the module needs to be introduced in Main.js, and the Import vueresource form './app '
When introduced, use Vue.use (Vueresource)
To invoke an interface in Tanslatetext:
this. $http. Get (' https://translate.yandex.net/api/v1.5/tr.json/translate?key= trnsl.1.1.20171103t033211z.f02fec6e631bce1f.d4c2b02b1d3981280c37eba265247f888c3e5215 ') The arguments that need to be passed are text and language
Use. Then () to receive the return value of HTTP
. then (reponse) =>{
Reponse under the body under the text[0] is the value we translated
})
Place the translated values in the page:
Returns a Translatedtext property under App.vue data and assigns the value to this property in response
Pass this property to Translateoutput, first introduce the Translateoutput component in App.vue, and enter in App.vue
<translateOutput></translateOutput>, by V-text binding Translatedtext This property, as follows:
<translateoutput v-text= "Translatedtext" &GT;&LT;/TRANSLATEOUTPUT&GT; after passing over, define a property in Translateoutput props:[" Translatedtext "], call this property in Translateoutput <div id=" Translateoutput ">
{{Translatedtext}}
</div>
Select also passes the value of language through V-model, passed as a parameter to the root component,
The created method does not need to be called and is executed by default.

A platform for 13:www.worktile.com employee collaboration
Vue
Vuex a state management mode
Vue-router
Webpack Module Packaging Tool
NodeJS running JavaScript on the server side
Express a simple and flexible node. JS WEB application Framework,
offers a range of powerful features to help you create Web apps and rich HTTP tools

MongoDB is a database based on distributed file storage designed to provide Web applications
Scalable, high-performance data storage solution.
Mongoose is an object model tool that makes MongoDB easy to work with in the node. JS Environment

Episode: Finding the PID command for port number 1099: netstat-ano|findstr "1099"

14:vue.js API

1. Global configuration
Vue.config is an object that contains the global configuration of Vue. You can modify its properties before starting the app.

Silent
Optionmergestrategies
Devtools
ErrorHandler
Warnhandler
Ignoredelements
Keycodes
Performance
Productiontip

To be continued .....

Vuejs basic knowledge and project summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.