Writing in the front
Spring enrollment is coming to an end, and many students must have received satisfactory offers. And the author is separated from one side about half a month long, and received millet’s second face. Compared with other interviews, Millet is more focused on you with the most concise language can be the most detailed expression of your ideas, the final practice of two hand tearing code questions.
1. Self-introduction and project introduction
slightly
2
2.1 What is VUEX? How to use it? Which functional scenarios use it?
- Reading-only states are concentrated in stores; The way to change that is to submit mutations, which is a simultaneous thing; Asynchronous logic should be encapsulated in actions.
- Import store and inject in main.js. Create a new directory store… Export.
- The scenarios include: status between components, music playing, login status, and adding to shopping cart in a one-page application
- State: Vuex uses a single state tree, where each application will contain only one store instance, but a single state tree is not incompatible with modularity. The state of the stored data cannot be modified directly.
- Mutations: The method defined by Mutations dynamically modifies the state or data in Vuex’s store
- Getters: A vUe-like computational property that filters data.
- Action: Actions can be understood as the method of treating the data in mutations into a method that can process the data asynchronously, simply speaking, it is to manipulate the data asynchronously. The View layer distributes actions through store.dispath.
Modules: When the project is particularly complex, we can make each module have its own state, mutation, action and getters, which makes the structure very clear and easy to manage
2.2 For reactive data binding, two-way binding mechanism: Object.defineProperty()
Vue implements bidirectional data binding mainly by using data hijacking combined with publiser-subscriber mode, hijacking setter and getter of each attribute through Object.defineProperty(), publishing messages to subscribers when data changes, and triggering corresponding listening callback. When a normal Javascript Object is passed to a Vue instance as its data option,Vue iterates over its properties, turning them into getters/setters with Object.defineProperty(). Getters/setters are invisible to the user, but internally they let Vue track dependencies and notify changes when properties are accessed and modified.
The two-way data binding of VUE takes MVVM as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor the data changes of its model, and uses Compile to parse and Compile template instructions (vUE is used to parse {{}}). Finally, watcher is used to build a communication bridge between observer and Compile to achieve data change – > view update; View Interactive Changes (INPUT) — > Data Model changes the bidirectional binding effect.
Data hijacking: Vue uses object.defineProperty () internally for bidirectional binding, which listens for set and GET events.
var data = { name: 'yck' }
observe(data)
let name = data.name // -> get value
data.name = 'yyy' // -> change value
function observe(obj) {
// Determine the type
if(! obj ||typeofobj ! = ='object') {
return
}
// object.keys (obj) converts objects into arrays
Object.keys(obj).forEach(key= > {
defineReactive(obj, key, obj[key])
})
}
function defineReactive(obj, key, val) {
// Recursive subattributes
observe(val)
Object.defineProperty(obj, key, {
enumerable: true.configurable: true.get: function reactiveGetter() {
console.log('get value')
return val
},
set: function reactiveSetter(newVal) {
console.log('change value')
val = newVal
}
})
}
Copy the code
Compare Proxy with Object.defineProperty
Object.defineproperty is already bidirectional binding, but it still has some drawbacks.
- Data hijacking can only be done on properties, so you need to deeply traverse the entire object and not listen for changes in the data on arrays
- While it is true that Vue can detect array data changes, it is a hack, and it is flawed.
Common attack methods and principles on web sites
- Cross-site scripting attacks (
xss
) : Malicious attackers pass throughweb
Page to insert malicioushtml
Code that is embedded when the user views the pageweb
The inside of thehtml
The code is executed for the specific purpose of maliciously attacking the user. sql
Injection:sql
To inject is to putsql
Command insert intoweb
The form is submitted, or the domain name is entered, or the query string of the page request is finally reached to trick the server into performing malicious executionsql
Purpose of the command. Specifically, the use of existing applications will be malicioussql
The command is injected into the background database engine for execution.cookie
Attack: Easy access to the current site through JScookie
You can open up any website and type it in the browser address barjavascript:alert(doucment.cookie)
, can immediately see the current site cookies, attackers can use this feature to obtain the user’s key information. Assuming the site relies solely on cookies for user authentication, an attacker can impersonate your identity to do something. Most browsers now support thecookie
Playing on theHttpOnly
If anyone has this markcookie
I can’t get throughjs
To get if able at keycookie
Mark it and enhance itcookie
Security.HTTP Headers
Attack: Using a browser to view any Web site, regardless of the technology and framework of your Web sitehttp
The agreement.http
The agreementResponse header
andcontent
Between, there is a blank line, namely two groupsCRLF(0x0D 0A)
Character this blank line marksheaders
And the end ofcontent
Start. An attacker takes advantage of this whenever the attacker has the means to inject arbitrary characters intoheaders
In, this attack can occur.- File upload attack: File upload vulnerability is to use the incomplete judgment of the file type uploaded by users, leading to the attacker to upload illegal files, so as to attack the website. You can upload a web Trojan, for example, and an attacker can get one if the directory in which the file is stored happens to have permission to execute the script
webshell
.
Diff principle in Vue
Keep in mind that rendering the real DOM can be expensive. For example, when we modify some data, rendering directly to the real DOM will cause the entire DOM tree to be redrawn and rearranged. Is it possible that instead of updating the whole DOM, we update only the small piece of DOM that we modify? The Diff algorithm helps us
Diff algorithm includes the following steps:
- with
JavaScript
Object structure representationDOM
Tree structure; And then use that tree to build a realDOM
Tree, insert it into the document - When the state changes, a new object tree is rebuilt. Then compare the new tree with the old tree (
diff
) to record the differences between the two trees - Apply the differences recorded in step 2 to the real ones built in Step 1
DOM
A tree (patch
), the view is updated
The diff algorithm is passedTree nodes of the same levelCompared with the tree layer by layer search traversal, so the time complexity is only O(n), is a fairly efficient algorithmWalk through the nodes of newVdom one by one to find its position in the oldVdom. If it is found, move the corresponding DOM element. If it is not found, it indicates that it is a new node, and then create a new node to insert. If there are unprocessed nodes in oldVdom after the traversal is complete, these nodes are deleted from newVdom. Delete them.
Vue template compilation principle
The entire process of converting a template to a view:
-
Vue. Js converts the template template into the render function by compilation, which is executed to obtain a virtual node tree
-
When the Model is operated on, the Watcher object in the corresponding Dep is fired. The Watcher object calls the corresponding UPDATE to modify the view. This process involves comparing the old and new virtual nodes and then DOM manipulation to update the view based on the comparison results.Let’s explain some of the concepts above:
-
Render functions: Render functions are used to generate the Virtual DOM. Vue recommends using templates to build our application interface. In the underlying implementation, Vue compiles templates into rendering functions, but we can also write rendering functions instead of templates for better control.
-
VNode virtual node: This can represent a real DOM node. A VNode can be rendered as a DOM node using the createElement method. Simply put, a VNode can be understood as a node description object, which describes how real DOM nodes should be created.
-
Patch (also known as patching algorithm) : The most core part of virtual DOM, it can render VNodes into real DOM. This process is to compare the differences between the old and new virtual nodes, and then find the nodes that need to be updated according to the comparison results. As can be seen from the meaning of the word, patch itself means patch and repair. Its actual function is to modify the existing DOM to realize the purpose of updating the view. Vue’s Virtual DOM Patching algorithm is based on the implementation of Snabbdom, and has made a lot of adjustments and improvements on these basis.
Tell me how much you know about Webpack
Basic Concepts:
- Entry:Indicates which module WebPack should use to build the start of its internal dependency graph.
- Loader:Webpack handles JS and JSON files by default, and loader configures WebPack to handle other types of files, turn them into valid modules for application use, and add them to dependency diagrams.
- Plugins:Loaders are used to transform certain types of modules, while plug-ins are used to perform a wider range of tasks. For example: package optimization, resource management, injection of environment variables, etc.
- Mode:Sets the optimization behavior of the current configuration file in both development and production environments. The default is production.
- Output:Indicates where WebPack should export the bundles it creates and how to name the files. There can be multiple entry files, but only one exit file.
The difference between Loader and Plugin:
- Loaderin
module.rules
That is, it exists as a parsing rule for the module. The type is array, one for each itemObject
, which describes what types of files (test
), what load is used (loader
) and the parameters used (options
). - Pluginin
plugins
Is configured separately. The type is array, one for each itemplugin
The arguments are passed in through the constructor.
In my personal understanding, plugin is more like a supplement to Loader, the two are complementary, loader is mostly fixed configuration, plugin can handle more flexible Settings.
Core role:
- Package compression: during development, project files are in various shapes and forms. At this time, Webpack can be used to pack and integrate different modules in an orderly manner. Modules are divided according to business, making the structure clear and readable. In the development process of the whole project, the code and files are relatively large. If the project is deployed, it will take up a lot of memory. Therefore, it can be compressed to reduce the original tens of meters to a few meters, or even hundreds of K.
- Compiler compatibility: I believe that in the actual development, due to historical reasons, various browsers left a lot of compatibility problems, on the one hand, we actively learn the new performance of browsers, on the other hand, we have to take into account the problems of old browsers. When configuring bebel-Loader, you can configure the predefined environment and make it compatible with old and new browsers by using the on-demand loader mechanism of Webpack. At the same time, since the browser can only read HTML, JS, etc., you can use Webpack to convert non-JS file modules into readable JS file modules.
- Ability development: Passed
webpack
thePlugin
Mechanism, on the basis of modular packaging and compiler compatibility, we can further achieve a series of functions such as loading on demand, code compression and so on, helping us to further improve the degree of automation, engineering efficiency and the quality of packaging output.
3 hand rip code problem
3.1 Thousandths of formatted digits
Use js to convert a given number to thousands of qubits, for example, 12345678 to 12,345,678.
This problem is relatively simple, can be used to solve the problem of the method also have a lot of, the simplest can be used regularization processing.
- regularization
let num = 12345678;
let str = num.toString();
let newStr = str.replace(/(\d)(? = (? :\d{3})+$)/g."$1");
Copy the code
- Splice a string
ToString () = toString() = toString(); toString() = toString(); toString() = toString(); Then, through a loop, the elements of the array are inserted backwards (unshift) to the beginning of the new array, the third or third times, the comma is inserted, and the new array is concatenated into a string.
let num = 12345678;
function Thousands(num){
// Convert a number to a string and split it into an array
let numArr = num.toString().split("");
let arr = [];
let count = 0;// For counting
for(let i = numArr.length-1; i>=0; i--){ count++;// Insert numbers from the end of numArr into arR
arr.unshift(numArr[i]);
// Append commas to every three digits of count. i! So when you get to the first digit, you don't have to put a comma before it.
if(! (count%3)&&i! = =0) arr.unshift(",");
}
// Concatenate arrays into strings
return arr.join("");
}
Thousands(num);
Copy the code
Disadvantages: bit by bit, poor performance, and must be converted to a string before an array.
- Get substrings with charAt(), mainly string concatenation
Get each character of the string and concatenate it.
let num = 12345678;
function Thousands(num){
// Convert a number to a string
let str = num.toString();
let res = "";// To receive a new concatenated string
let count = 0;// For counting
for(let i = str.length-1; i>=0; i--){ count++;// Insert numbers from the end of numArr into arR
res = str.charAt(i) + res;
// Append commas to every three digits of count. i! So when you get to the first digit, you don't have to put a comma before it.
if(! (count%3)&&i! = =0) res = ', ' + res;
}
// Concatenate arrays into strings
return res;
}
Thousands(num);
Copy the code
Disadvantages: still need to be segmented splicing.
- Each three bits are cut and spliced
Each time you take the last three bits of the string and put them into a new empty string and concatenate the last three bits of the string. Then you slice off the last three bits of the array until the length is less than three.
let num=123345678;
function Thousands(num){
// Convert a number to a string
let str = num.toString();
let res = "";// To receive a new concatenated string
while(str.length>3){
res = "," + str.slice(-3) + res;
str = str.slice(0,str.length-3)}if(str) return str + res;
};
Thousands(num);
Copy the code
3.2 Comparing the properties and values of two objects
Title description:
obj1 = {name:"wenbo".age:12.score: [120.121.113]};
obj2 = {age:12.name:"wenbo".score: [120.121.113]};
Copy the code
- Walk through and compare
Idea: Compare the traversal values of two objects
function fun(obj1,obj2){
// Check whether obj1 and obj2 are Object types
let o1 = obj1 instanceof Object;
let o2 = obj2 instanceof Object;
// If there are two types that are not object types, we can compare them directly
if(! o1 || ! o2)return obj1 === obj2;
// If two are object types and the number of key-value pairs is different
if(Object.keys(obj1).length! = =Object.keys(obj2).length) return false;
// If none of the above conditions is true, the traversal comparison is performed
for(let key in obj1){
// We need to check whether the value corresponding to this key of both objects is the object type
let flag1 = obj1[key] instanceof Object;
let flag2 = obj2[key] instanceof Object;
if(flag1 && flag2){
fun(obj1[key],obj2[key])
}else if(obj1[key] ! == obj2[key]){return false; }}return true;
}
let obj1 = {name:"wenbo".age:12.score: [120.121.113]};
let obj2 = {age:12.name:"wenbo".score: [120.121.113]};
fun(obj1,obj2);
Copy the code
Or:
function fun(obj1,obj2){
// Check whether obj1 and obj2 are Object types
let o1 = obj1 instanceof Object;
let o2 = obj2 instanceof Object;
// If there are two types that are not object types, we can compare them directly
if(! o1 || ! o2)return obj1 === obj2;
// If two are object types and the number of key-value pairs is different
if(Object.keys(obj1).length! = =Object.keys(obj2).length) return false;
// Take the property names of obj1 and obj2
let obj1Props = Object.getOwnPropertyNames(obj1);
// Loop through the attribute name and check whether the attribute values are consistent
for (let i = 0; i < obj1Props.length; i++) {
let propName = obj1Props[i];
// We need to check whether the value corresponding to this key of both objects is the object type
let flag1 = obj1[propName] instanceof Object;
let flag2 = obj2[propName] instanceof Object;
if(flag1 && flag2){
fun(obj1[propName],obj2[propName])
}else if(obj1[propName] ! == obj2[propName]){return false; }}return true;
}
let obj1 = {name:"wenbo".age:12.score: [120.121.113]};
let obj2 = {age:12.name:"wenbo".score: [120.121.113]};
console.log(fun(obj1,obj2));;
Copy the code
- Questions to consider
When the Object traversal process, encountered the Object attribute type, and pointed to the Object, then need to consider the above code can run successfully? Such as:
let obj1 = {name:"wenbo".age:12.score: [120.121.113]};
obj1.temp = obj1;
let obj2 = {age:12.name:"wenbo".score: [120.121.113};
obj2.temp = obj1;
Copy the code
Create an array and store the key values iterated over by obj1 in the array. The next iteration will find the same value and skip the comparison.
Refer to the article
- 1. What the Interviewer Wants to know when he Asks Webpack:
https://mp.weixin.qq.com/s/RmcMWzkAiOrOOyxtPSZDUg
- 2. Webpack interview Questions Summary:
https://juejin.cn/post/6844903877771264013