Saturday, April 11, 2020

Fancy representation of JavaScript topics 26 letters

Look at the effect first.

Let's think first:
 // What does the following sentence print? 
[+ [] [0] + []] [ 0] [1 ]
We look directly at the effect:


If you feel that printing a letter is too addictive, print a word?
 // Note that printing in Chrome

[[] [0] + []] [ 0] [5 ] + [[] [[] [0] + []] [ 0] [4 ] + [[] [0] + []] [ 0] [5 ] + [[] [0] + []] [ 0] [1 ] + [[] [0] + []] [ 0] [2 ]] + []] [0] [ 8] + [[[] == []] [ 0] + [] [ 0] [2] + [[] [[] [ 0] + [] [ 0] [4] + [[] [ 0] + [] [ 0] [5] + [[] [ 0] + [] [ 0] [1] + [[] [ 0] + [] [ 0] [2] + []] [ 0] [6 ] + [[] [[] [0] + []] [ 0] [4 ] + [[] [0] + []] [ 0] [5 ] + [[] [0] + []] [ 0] [1 ] + [[] [0] + []] [ 0] [2 ]] + []] [0] [ 23] + [[] [0 ] + []] [0] [ 3] + [[] [[] [ 0] + [] [ 0] [4] + [[] [ 0] + [] [ 0] [5] + [[] [ 0] + [] [ 0] [1] + [[] [ 0] + [] [ 0] [2] + []] [ 0] [8 ] + [+ [1+[] [ 0] + [] [ 0] [3] + 309] [0 ] + []] [0] [ 7] + [[] [[] [ 0] + [] [ 0] [4] + [[] [ 0] + [] [ 0] [5] + [[] [ 0] + [] [ 0] [1] + [[] [ 0] + [] [ 0] [2] + []] [ 0] [6 ] + [[] [0] + []] [ 0] [0 ]
Let's look at the effect again:



Basic test

If you want to understand how the above is implemented, first check your own understanding of JavaScript implicit type conversion:

 // What will the following values print? 
console.log (+ []);
console.log ( 1+ []);
console.log (+ undefined);
console.log ([] == []);
console.log (+ [] == + []); 

If you cannot accurately state the above results, or if you want to better understand the above conversion process, we recommend that you first look at two articles:

JavaScript thematic headache type conversion (Part 1) .md

JavaScript topic headache type conversion (bottom) .md

Start Decryption

First effect:

  [] [0]

Because the empty array does not have the first element, undefined will be printed

Second effect:

  undefined + []

undefined + [] is equivalent to undefined + “” resulting in a “undefined” string.

This time has obtained an undefined string, we can only use the corresponding letters through the subscript.

However, if we don't use parentheses, how do we get the value? At this point, we need to use a trick:

The third effect:

  ['undefined'] [ 0] [0 ]

This time we get the “u” letter, by changing the subscript, we can get u, n, d, e, f, i total of 6 letters

Isn't it interesting, but that's just the beginning.

NaN

First effect:

  +undefined

is equivalent to Number (undefined), the result is NaN

Second effect:

  NaN+ []

equivalent to NaN+“” result to NaN string

The third effect:

  [NaN] [0 ] [1]

In this way we can get the letter a.

false

First effect:

  [] == []

The result is naturally false

Note, because of the two previous examples, you may have gradually understood that when taking out a value, if you turn into a string, if you take the letter of the subscript

Second effect:

 // convert to string by value + []
false + []

The third effect:

 // take the letter by [value] [0] [n]
['false'] [ 0] [0 
]

we can take out the f letter.

In this way, we can take out the five letters “f”, “a”, “l”, “s”, “e”.

true

Take a direct look at the core steps:

  + [] == + []

equivalent to comparing “” == “”, the result is naturally true

The rest of us must have been cooked.

The

letters obtained by the above 4 methods are still limited, and we need some other way to get more letters.

Infinity

Note: In the front we have taken the letter e.

  + (“1e309")

to a number, the equivalent of 1 times 10 309 times, greater than the maximum number of JavaScript, so the result will be Infinity, and the rest of the The steps are the same as above and will not be discussed later.

We can remove t and y from it.

function

Note: By this point we have obtained u n d e f i t r f a l s t y, from which we can spell the string “find”.

[]["find"]

displays the find function of the array, with the result:

function find() { [native code] }

With this approach, we can take out c o v.

But note: taking the letter v this way will have compatibility issues!!!

The magic constructor

Note that we already have 17 letters, we can now spell “constructor”!

constructor can be a magical property because through it we can get constructors for various types of value objects!

0["constructor"] // function Number() { [native code] }

""["constructor"] // function String() { [native code] }

...

In the above way, we can take m, g

Perhaps we wonder, how does“” mean it?

[] + [] === "" // true

name

With m, we can now spell the name, but what is the use of name?

"to" + ""["constructor"]["name"] // "toString"

Our ultimate goal is to spell out the “toString” string

The almight toString

The reason

we spelled out toString is because using toString this method can represent 26 letters!

At this time, we would like to introduce the usual obscure, but here indeed the final protagonist toString method!

The following quote from W3C school:

Role:

The
toString () method converts a Number object to a string and returns the result.

Usage:

NumberObject.toString (radix)

Parameter Explanation:

radix: Represents the radix of a number, making an integer between 2 and 36. If this parameter is omitted, base 10 is used. Note, however, that if the parameter is a value other than 10, the ECMAScript standard allows the implementation to return arbitrary values

To take an example:

var number = new Number(10);
number.toString('16');

That is, 10 is represented in hexadecomals. The above example prints the result “a”.

Note that radix can represent 36 maximum!!!!

var number = new Number(35);
number.toString('36');

The printed letter is “z”! In this way, we can represent all the remaining letters!

But how do we use this toString method? To be precise, how do we generate a number object? Do you still need to spell new Number?

I

don't even need it! At this point, the advantages of JavaScript implicit type conversion are highlighted:

35["toString"](36) // z

Note: By this time, we also had to use ()!

By this point, we can already show all the letters, some are very easy to show, some are somewhat troublesome, and the display is very long, such as the letter p:

25[[[+[] == +[]][0] + []][0][0]+[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][6] + [[] + []][0][[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][3]+[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][6]+[[][0] + []][0][1]+[[[] == []][0] + []][0][3]+[[+[] == +[]][0] + []][0][0]+[[+[] == +[]][0] + []][0][1]+[[][0] + []][0][0]+[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][3]+[[+[] == +[]][0] + []][0][0]+[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][6]+[[+[] == +[]][0] + []][0][1]][[[][0] + []][0][1]+[+[][0] + []][0][1]+[0[[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][3]+[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][6]+[[][0] + []][0][1]+[[[] == []][0] + []][0][3]+[[+[] == +[]][0] + []][0][0]+[[+[] == +[]][0] + []][0][1]+[[][0] + []][0][0]+[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][3]+[[+[] == +[]][0] + []][0][0]+[[][[[][0] + []][0][4]+[[][0] + []][0][5]+[[][0] + []][0][1]+[[][0] + []][0][2]] + []][0][6]+[[+[] == +[]][0] + []][0][1]]+[]][0][11]+[[][0] + []][0][3]]](27)

Friday, April 10, 2020

The Basics of JS Must Know “Strict Mode 'use strict'”


JS's strict mode'use strict'should be familiar with knowledge, literally to explain is to follow strict behavior patterns to Write code. But what are the rules that constrain us to use strict mode to regulate our own code during development? So the purpose of this article is simply to deepen the understanding of the strict model once again. Although this article is the basics, I hope it helps you.

Definitions of Strict Mode

use strict is a (strict) running mode added to ECMAscript5, which makes Javascript Operate in stricter conditions. The implementation of strict mode makes your program or function follow a strict operating environment.

The purpose of establishing the “strict model” is to:

  • Eliminate some unreasonable and inrigorous aspects of Javascript syntax and reduce some weird behavior;
  • Eliminate some insecure aspects of code operation and ensure the safe operation of code;
  • Improve compiler efficiency and increase running speed;
  • Padders
  • for future versions of Javascript.

Use of strict mode

Enable strict mode for scripts

To open strict mode for the entire script file, you need to put a specific statement “use strict”before all statements; (or 'use strict';)

 // syntax for opening strict mode for the entire script
“ use strict”;
var v =  “Hi! I'm a strict mode script!” 
;
This syntax is stuck if you merge a script in strict mode with a script in non-strict mode: the merge appears to be strict mode. And vice versa: non-strict merging is strictly seeming non-strict. It is therefore recommended to either switch on strict mode or not use non-strict mode.

Enable strict mode for functions

To turn on strict mode for a function, you have to put “use strict”; (or 'use strict' ;) declarations are placed without leakage before all statements of the function body.

 function  strict ( ) {
 // function level strict mode syntax
 'use strict';
 function  nested ( ) { 
 return ” And so am I!” ; 
 }
 return ” Hi! I'm a strict mode function!  “ + nested ();
}

function  notStrict ( ) { 
 return ” I'm not strict.” ; 
}

Specifications for Strict Mode

variable

Rules for using variables in strict mode

  1. Do not allow accidental creation of global variables
  2. Declaring variables cannot be deleted using delete operator
  3. Do not use reserved words (e.g. implements, interface, let, package, private, protecte, public, static, and yield identifiers) as variable names

Rule 1

 // create a global variable called message
message = “Hello JavaScript! “; //this line will throw ReferenceError 

Rule 2

 var x;
delete x; //!!! syntax error

eval(” var y; delete y;”); //!!! syntax error

Rule 3

 var private = 123; // !!! syntax error
var public = ' hello '; //!!! syntax error

object

Rules for using objects in strict mode

  1. A value for a read-only attribute throws TypeError
  2. Using the delete operator on non-configurable properties throws TypeError
  3. Adding properties to non-extensible objects throws TypeError
  4. When using object literal, attribute names must be unique

Rule 1

 // give a value to the read-only property
var obj2 = { get x () { return  17;}};
obj2.x = 5; // Throw TypeError error

// give a value to a non-writing property
var obj1 = {};
Object.defineProperty (obj1, “ x”, {  value: 42, writable:   false});
obj1.x = 9; // Throw TypeError error

Rule 2

  delete Object.prototype; // Throw TypeError error

Rule 3

 // give a value to the new property of an object that is not expensible
var fixed = {};
Object.preventExtensions (fixed);
fixed.newProp = “ohai”; // Throw TypeError error

Rule 4

  var o = {  p: 1, p: 2 }; //!!!! syntax error

Functions

Rules for using functions in strict mode

  1. Requires unique parameters for named functions
 function  sum ( a, a, c){ //!!! syntax error
 return a +a+c; // code running here will go wrong
}

eval vs. arguments

Rules for using eval and arguments in strict mode

  1. eval does not create variables or functions in the context of
  2. eval and arguments cannot be bound or assigned by program syntax
  3. The value of the parameter does not change as the value of the arguments object changes
  4. The use of arguments.callee is prohibited
 function  doSomething ( ) {
 eval(” var x=10");
 alert (x); //Throw TypeError error
}

Rule 2All attempts below will cause a syntax error:


 eval =  17;
arguments++;
++eval;
var obj = { set p (arguments) {}};
var  eval;
try {} catch ( arguments) {}
function  x ( eval){}
function  arguments ( ) {}
var y = function  eval ( ) {};
var f = new  Function (“arguments”, “ 'use strict'; return 17;”); 

Rule 3

 function  f ( a){
 a = 42;
 return [Aa arguments[ 0]];
}
var pair = f ( 17);
console.assert (pair [ 0] ==42 );
console.assert (pair [ 1] ===17 );

Rule 4

 var f = function (){ 
 return arguments.callee; 
};
f (); //throw a type error

Suppressing traversing the call stack inside a function

 function  restricted ( ) {
 restricted.caller; //throws a type error
 restricted.arguments; //throw a type error
}

Static Bindings

  1. Prohibit the use of the with statement
  2. eval () declaration variables and functions are valid only in the scope of the current eval

Rule 1

 var x =  17;
with (obj) { //!!! syntax error
 // If strict mode is not enabled, the x in with will point to the x above with, or obj.x? 
 // If you don't run the code, we can't know it, so this code does not allow the engine to be optimized, and the speed will change. Slow. 
 x;
}

Rule 2

 var result = eval(” var x=10, y=11; x+y”);
alert (result); //21

this points to

    This
  1. in a function in a global scope no longer points to global but undefined.
  2. If you forget to add new when using the constructor, this no longer points to the global object, but instead undefined
 // Rule 1
function  bar ( ) {
 console.log ( this)
}
bar () //undefined


// Rule 2
function  Person ( ) {
 this.name= “ Vincent” // Uncaught TypeError: Unset property 'name' of undefined
}

Person () //error is reported. If you forget to add new, this no longer points to global object, but undefined.name. 

summary

Now a lot of people are working with various frameworks and tools, but in fact, there is no problem in our development, because it brings efficiency gains. But all things can grow without root, so the foundation is always the basic core. I also know that everyone's time is limited, and it's not enough to take care of it. But I recommend taking some time on the basis, even if it takes 10 to 20 minutes a day to take a look at the basics, because every time I read it, there will be a certain gain.

I don't have a good technical skills or a solid foundation, so I remind myself every day not to stop moving forward.


### References
- [ JavaScript Advanced Programming (3rd Edition)] ( https://item.jd.com/10951037.html)
- [Strict Mode MDN] ( https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Strict_mode 
)

Full version of JavaScript for Loop Loop Guide


Take a few minutes to relive the basics of the JavaScript loop guide and remember a figure



During front-end development, we often use JavaScript to provide a lot of loop and iteration methods, commonfor, for... of,for... in,while, Array.forEach, as well as Array.* (There are also some Array methods similar to loop/iterator: Array.values (), Array.keys (), Array.map () , Array.reducer (), etc.), and these are very basic things, there must be people who think these are very basic. Something, what's good looking at? The purpose of these things is to be framed and brainized. So it's simple to make a diagram of a JS loop. Integrate cluttered, fragmented knowledge into everything, making it easier to remember thebasics.



Simple Loop
for
The for loop repeats as long as certain conditions are met. It is usually used to execute a code block a certain number of times.

array loop


const arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i])
}

break statement

Use break statement to terminate a loop


 for (  let i = 0 ;; i++) {
 console.log ( ' loop ')
 break
}

// output: loop

In this case, in the for loop, the break keyword exits the loop when it encounters the loop.

continue statement

The continue statement can be used to continue execution (skip the rest of the code block and go to the next loop)


 for (  let i = 0 ; i < 3; i++) {
 if (i === 2)  continue
 console.log (i)
}

// output: 0, 1


The above code can enter the result, when condition i === 2 is established, encounter continue keyword to skip and proceed to the next loop.

for…of

The for... of statement creates a loop on an iterable object (including Array, Map, Set, arguments, and so on), with each unique property of the value with one iteration.

string string loop



let string = 'text'

for (let value of string) {
  console.log(value) // output "t", "e", "x", "t"
}

array array loop



let arr = [0, 1, 2]
for (let value of arr) {
  console.log(value) // output 0, 1, 2
}

objects object loop

For... of loop works only for iterable values, objects are not iterable, so it is not feasible to loop objects directly using for... of. The following example:


let object = { a: 1, b: 2, c: 3 }

for (let value of object) // Error: object is not iterable
  console.log(value)

You can convert an object to an iterable object using the built-in Object method:.keys (),.values () or.entries (), see the following example:

let enumerable = { property : 1, method : () => {} };

for (let key of Object.keys( enumerable )) console.log(key);
> property
> method

for (let value of Object.values( enumerable )) console.log(value);
> 1
> () => {}

for (let entry of Object.entries( enumerable )) console.log(entry);
> (2) ["prop", 1]
> (2) ["meth", ƒ()]

It can also be achieved by using a for... in loop without using the built-in Object method.

for…in

A for... in loop is a special type of loop that traverses the properties of an object or the elements of an array. When traversing objects, you can display enumerable object properties


let object = { a: 1, b: 2, c: 3, method: () => {} }

for (let value in object) {
  console.log(value, object[value])
}

// output: 1, 2, 3, () => { }

while

A while statement executes its block as long as the specified condition evaluates to true (true).

 let c =  0

while (c++ < 5) {
 console.log (c)
}

// output: 1, 2, 3, 4, 5 

do... while

is very similar to while, while the do... while statement repeats until the specified condition evaluates to a false value (false).

 var i =  1
do {
 console.log (i)
 i++
} while (i <= 5)

// output: 1, 2, 3, 4, 5 

Arrays Loops



Array has several iteration methods. Usually we recommend using the built-in Array method for loop operations instead of using for or while loops. The array method is attached to the Array.prototype property, which means that it is used directly from the array object.

For example, usingArray.forEach ()method to manipulate an array

forEach

Definition: The forEach method executs the given function once on each element of the array.
Return value: none


let arr = ['jack', 'tom', 'vincent']

arr.forEach((name) => console.log(`My name is ${name}`))

//output
// My name is jack
// My name is tom
// My name is vincent

every

Definition: checks whether all elements of the array meet the judgment criteria, returns true, otherwise false
Return value: boolean


const isBelowThreshold = (currentValue = currentValue < 40)
const array1 = [1, 30, 39, 29, 10, 13]

console.log(array1.every(isBelowThreshold))

// output: true

 some



Definition: whether there are elements in the array that satisfy the judgment criteria. If at least one of the judgment conditions is satisfied, the return value isfalse ifnone are satisfied:
boolean

filter

Definition: Execres the given function once on each element of the array, returning a new array
Return value: New array


const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

map

Definition: The method creates a new array whose result is the return value after each element of the array has been called once.
Return value: New array


const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

reduce && reduceRight



Definition: Thereducemethod performs a reducer function (in ascending order) supplied by you on each element of the array, summarising its results as A single return value.


const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15


Definition:reduceRightmethod accepts a function as accumulator and each value of an array (right to left) ) to reduce it to a single value.


const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]

find()& findIndex()



Definition: Thefind method is used to find the first array member that matches the condition, and returns the member if there are no members that match the condition undefined.


const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12


Definition:findIndexreturns the position of the first array member that matches the condition, or -1 if all members do not match the condition.


const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3


The Git branch development specification you must know

Git is currently the most popular source control tool.
For specification development, keep code commit records and git branch structure clear, convenient for subsequent maintenance, now regulate git related operations.


Branch Naming

master branch


  • Master is the master branch, which is also used to deploy production environment, ensuring the stability of master branch
  • Master branches are generally incorporated by development and hotfix branches, you cannot modify the code at any time.

develop branch

  • develop is a development branch, always keeping the latest finished and bug-fixed code
  • In general, feature branches are created under the development branch
feature branch

  • Create feature branches based on development when developing new features
  • Branch naming: feature/beginning with feature branches, naming rules: feature/user_module, feature/ cart_module
release branch

  • release is the pre-line branch, release the prediction phase, will release the branch code for the baseline prediction

When a set of features is developed, it will first merge into the development branch, and when it enters the prediction, it will Create areleasebranch.
If there are bugs that need to be fixed during the testing process, the developer will use the The branch is fixed and committed.
When the test is complete, merge thereleasebranch into the masterand develop branches, at this point Masteris the latest code for online use. 

hotfix branch


  • Branch naming: hotfix/beginning with fix branch, its naming rules are the same as feature


  •  branch is similar to If there is an emergency problem online, you need to fix it in time, using master branch as baseline, create a hotfix branch, after the fix is complete, you need to merge into master branch and develop branch

Common Tasks
Add new features


( dev) $: git checkout -b feature/xxx # Create feature branch from dev
(feature/xxx) $: blabla # development
(feature/xxx) $: git add xxx
(feature/xxx) $: git commit -m 'commit comment'
(dev) $: git merge feature/xxx —no-ff  # incorporate feature branches into dev

Fix emergency bugs 



( master) $: git checkout -b hotfix/xxx # Create a hotfix branch from master
(hotfix/xxx) $: blabla # development
(hotfix/xxx) $: git add xxx
(hotfix/xxx) $: git commit -m 'commit comment'
(master) $: git merge hotfix/xxx —no-ff  # Combine the hotfix branch into master and go online to production
(dev) $: git merge hotfix/xxx —no-ff  # merge the hotfix branch into dev, synchronize the code

Test Environment Code 



 ( release) $: git merge dev —no-ff # merge dev branch into release, then pull and test in the test environment 

Production environment online 



( master) $: git merge   release —no-ff # Combining release test code into master, operation and maintenance personnel
(master) $: git tag -a v0 .1 -m 'deployment Package version name ' #给版本命名,打Tag  

 Log specification

In a teamwork project, the developer often needs to submit code to fix bugs or implement new features. The files in the project, what features are implemented and what problems are solved, will be lost and time spent reading the code. But good log specification commit messages writing helps us, and it also reflects whether a developer is a good collaborator.

Writing good Commit messages can achieve 3 important purposes:


  • Accelerate the review process


  • Help us write good release log



  • To let the later defenders understand the specific changes in the code and why features are added
Currently, the community has a variety of writing standards for Commit message. The Angular specification is currently the most widely used writing, more rational and systematic. As shown in the following figure:


Basic syntax for Commit messages


Angular Git Commit Guidelines is widely used in the industry.

The format is:

<type>: <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>

  • type: The type of commit, such as bugfix docs style, etc.
  • scope: Scope of this commit
  • subject: The main thrust of this commit is briefly explained. In the original text, several points were specifically emphasized 1. Using a praying sentence, is not very familiar and unfamiliar word, to send the door in this praying sentence 2. Do not uppercase the first letter 3. No need to add a mocking at the end
  • body: We need to describe this commit in detail, such as the motive of this change, if you need to enter a line, use |
  • footer: Describe the issue or break change associated with it, see the case
Category description for Type:



  • feat: adding new features
  • fix: fixing bugs
  • docs: only modified documentation
  • style: Just modify spaces, formatting indents, all good, etc., do not change the code logic
  • refactor: code refactoring, no new features or bug fixes
  • perf: Increase code for performance testing
  • test: Add test cases
  • chore: Change build flow, or add dependency libraries, tools, etc.
Commit messages format requirements



# Title line: 50 characters , describing the main changes
#
# Body: More detailed description text, recommended 72 characters or less. Information to be described includes:
#
# Why is this change required? It may be used to fix a bug, add a feature, improve performance, reliability, stability, etc.
# How does he solve this problem? Describe the steps to resolve the problem
#* Are there side effects, risks? 
#
# If desired, you can add a link to the issue address or other documents 

Is it appropriate to import on demand in vue.js components, or to import globally?

Beginners don't understand, ask: On-demand import is appropriate in vue.js components, or global import is appropriate? Which way will make the final packed volume smaller?

Not half written yet, so much volume [cover face.jpg]:



code solutions


Direct creation of JS file in main.js is the introduction of use; global too large;


import Vue from 'vue'
import {
  Collapse,
  CollapseItem,
  Button,
  Row,
  progress,
  Col,
  Form,
  FormItem,
  InputNumber,
  Input,
  Select,
  Option,
  Message,
  MessageBox,
  Scrollbar,
  Menu,
  MenuItemGroup,
  Submenu,
  MenuItem,
  Tooltip,
  Breadcrumb,
  BreadcrumbItem,
  Dropdown,
  DropdownMenu,
  DropdownItem,
  Badge,
  Table,
  TableColumn,
  Tag,
  Tabs,
  TabPane,
  Timeline,
  TimelineItem,
  Card,
  Pagination,
  Notification,
  Dialog,
  DatePicker,
  Tree,
  Upload,
  Carousel,
  CarouselItem,
  Cascader
} from 'element-ui'
Message.install = () => {
  Vue.prototype.$message = Message
}
MessageBox.install = () => {
  Vue.prototype.$confirm = MessageBox.confirm
}
Notification.install = () => {
  Vue.prototype.$notify = Notification
}
Vue.use(InputNumber)
Vue.use(Collapse)
Vue.use(CollapseItem)
Vue.use(progress )
Vue.use(Button)
Vue.use(Row)
Vue.use(Col)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
Vue.use(Message)
Vue.use(MessageBox)
Vue.use(Notification)
Vue.use(Scrollbar)
Vue.use(Menu)
Vue.use(MenuItemGroup)
Vue.use(Submenu)
Vue.use(MenuItem)
Vue.use(Tooltip)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Dropdown)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Badge)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Tag)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(Timeline)
Vue.use(TimelineItem)
Vue.use(Card)
Vue.use(Pagination)
Vue.use(Dialog)
Vue.use(DatePicker)
Vue.use(Select)
Vue.use(Option)
Vue.use(Tree)
Vue.use(Upload)
Vue.use(Carousel)
Vue.use(CarouselItem)
Vue.use(Cascader)

addEventListener adds click event, click delete button parent node will report error, use onclick event but not. What is this reason?

Guys, I am self-learning Meng new because in the practice encountered bugs also went to find but I don't know why, addEventListener deleted Why does the node to be taken away is not a child of this node.

Can achieve the effect of deletion, but that is, there will be errors reported using the traditional method of registration, there will be no error report, but the best sister, ask the big guys to point it, I really don't know why.


<div class="box">
      <textarea name="" id="" cols="30" rows="10"></textarea>
      <button>published</button>
      <ul></ul>
    </div>
    <script>
      const text = document.querySelector("textarea");
      const btn = document.querySelector("button");
      let ul = document.querySelector("ul");
      btn.addEventListener("click", function (e) {
        if (text.value == "") {
          alert("Empty content cannot be published");
        } else if (text.value.length > 120) {
          alert("Content cannot exceed 120 words");
          text.value = "";
        } else {
          var li = document.createElement("li");
          li.innerHTML = text.value.trim() + ` <a href="javascript:;">Delete</a>`;
          ul.insertBefore(li, ul.children[0]);
          text.value = "";
          var as = document.querySelectorAll("ul a");

          for (var i = 0; i < as.length; i++) {
            // Tradition onclick
            // as[i].onclick = function () {
            //   ul.removeChild(this.parentNode);
            //   console.log(this.parentNode);
            //   console.log(as);
            // };
            // addEventListener Event Listening;
            as[i].addEventListener("click", function () {
              ul.removeChild(this.parentNode);
              console.log(this.parentNode);
              console.log(as);
            });
          }
        }
      });
      document.addEventListener("keyup", function (e) {
        if (e.keyCode == 13 && e.ctrlKey == true) {
          btn.click();
        }
      });
    </script>


solutions


You bind a click event to execute it in btn's click event.

So every time btn, will re-add the event binding.

Comb the process:

Add a li > a, recorded as A;
for loop to bind the event to A;
Add a li > a, recorded as B;
The for loop gives A/B all bind events too.
At this point A has been tied twice,That is, when the callback is triggered twice,The first callback has been deleted,The second callback of course can't find the DOM。

And onclick is an attribute assigned, equal to overwriting the first time, so the callback does not fire repeatedly.

If you want to use addEventListener, you should use event proxies (also called event delegates), bubbling. 

The applet pagings are also pagings when loading, how to fix it?

The applet cloud development related,There are 30 messages in the collection,They are sorted in descending order by time

`db.collection ('posts')
.orderBy ('created_at', 'desc')
.skip (posts.length)
.get`

There is no problem at the beginning when the content is less,When testing more things found that the sort is wrong。 The following is the database content is in ascending order, so the obtained content is also ascending order, by descending order the content is inverted.
But because of page-loading, the content obtained in the first page is sorted and displayed. Although the content of the second page is newer than the first page, but is obtained at the back of the first page, it is ranked behind the first page, causing me to post new content, will also be displayed in the back, how to deal with this, please the big guy Solve the confusion.

vue jsx binding onmouseover invalid?


 return <div iid={component.iid} class="component_title_div" onClick={vm.componentTabClick} onmouseover={vm.mouseOver}  >
                        {component.cname}
        </div>

vue never triggers when binding onmouseover with jsx, onClick triggers normally, why?
onMouseOver does not work either 

Clamp.js plugin, resolving text multi-line omitting, IE compatible and other browsers

Download
Clamp.js Project Address: https://github.com/josephschmitt/Clamp.js

Introduced


<!-- Text Multiline Omit Plugin -->
<script src="./assets/js/common/clamp.min.js"></script>


Use
Text needs to use p tag span not


// Text omitted, compatible with browsers such as IE
var newsSummary = $('.news-right-items-single-content-summary');
for (var i = 0; i < newsSummary.length; i++) {
    $clamp(newsSummary[i], { clamp: 2 });   //Show two rows
}


How to gracefully use anti-vibration flow in Vue

1. What is anti-vibration flow

Stabilizing: Prevents repeated click triggering events

First of all, what is shaking? Shaking is a shiver! Originally, now three! I don't know if the old iron mind is very picturesque! Ha ha ha ha ha ha ha ha ha

A typical application is to prevent users from repeatedly requesting data.

Code implementation points: set a timer, go through closures, grab timer variables, control timer additions and clears


Directly on the code


  function debounce(fn, time) {
      let _arguments = arguments
      let timeout = null
      return function () {
          if (timeout) {
              clearTimeout(timeout)
          }
          timeout = setTimeout(() => {
              fn.call(this, _arguments)
          }, time);
      }
  }

Throw: The task will only be executed once during a given interval

Everyone has played FPS games (haven't played???? (Shoot knows it!) The speed of the item is certain, will not increase because you click the mouse faster.

Key to Code Implementation: Determine whether code needs to be executed by a boolean variable as a state

Directly on the code


  function throttle(fn, time) {
      let _arguments = arguments
      let canRun = true 
      return function () {
          if (!canRun) return
          canRun = false
          setTimeout(() => {
              fn.call(this, _arguments)
              canRun = true
          }, time);
      }
  }


2. Elegant use in Vue 

 My Application Scene: Avatar Cropping Component, image image stabilization after scrolling wheel zoom