A, com 1

xiang wang

1. Vue response type principle

Answer: Vue2 is object.defineProperty and observer mode. Vue3 is a proxy and observer mode

  • Vue official website – In-depth responsive principles

1) Precautions for detecting changes

Due to JavaScript limitations, Vue cannot detect array and object changes

1.1) For objects

Vue cannot detect the addition or removal of property. Since Vue performs getter/setter conversions on property when it initializes the instance, the property must exist on the data object for Vue to convert it to reactive. Such as:

var vm = new Vue({ data: {a:1}})// 'vm.a' is responsive vm.b = 2 // 'vm.b' is non-responsive
Copy the code

Vue does not allow dynamic root-level responsive properties to be added to already created instances. However, you can add responsive properties to nested objects using the vue.set (Object, propertyName, value) method. For example, for:

Vue.set(vm.someObject, 'b'.2)
Copy the code

You can also use the vm.$set instance method, which is also an alias for the global vue.set method:

this.$set(this.someObject,'b'.2)
Copy the code
1.2) for arrays

Vue cannot detect changes to the following arrays:

  1. When you set an array item directly using an index, for example:vm.items[indexOfItem] = newValue
  2. When you modify the length of an array, for example:vm.items.length = newLength

Here’s an example:

var vm = new Vue({
    data: {
        items: ['a'.'b'.'c'],}}); vm.items[1] = 'x'; // Not responsive
vm.items.length = 2; // Not responsive
Copy the code

To solve the first type of problem, the following two methods can achieve the same effect as vm.items[indexOfItem] = newValue, and also trigger status updates within a responsive system:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
Copy the code
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
Copy the code

You can also use the vm.$set instance method, which is an alias for the global method vue. set:

vm.$set(vm.items, indexOfItem, newValue)
Copy the code

To solve the second type of problem, you can use Splice:

vm.items.splice(newLength)
Copy the code

2. Whether the Webpack Loader has a sequence and is different from plug-ins

Answer: Borrows the idea of functional function composition: – Webpack loads from right to left

2.0 Webpack Loader and plugin differences and implementation of loader and plug-in

Loader is actually a converter, you input the content to translate, essentially there is no change, just like Chinese translation into English

Compared with Loader, plugin mechanism is more flexible, it can change the output during the running of WebPack. It simply adds to the output.

Realize the Loader and plug-in zhuanlan.zhihu.com/p/28245984

module: {rules: [{test:/\.js$/,
            use:[{
                loader:'babel-loader'.options: {presets: ['react']}}]}Copy the code

2.1 the url – loader

Url-loader introduces images and is an enhanced version of file-loader

Url-loader will encode our image into another string using base64, which can be recognized by web pages. The advantage of this is that it reduces the image request. As long as you request back to the page, the image will come, which can reduce the network request. The string will become extremely large, making the loaded file extremely large

So if the image is too small, there’s no need for it to re-request the image, just write it to the page and let the browser parse it. If the image is too large, don’t let it encode it. See how this works

{
    test:/\.jpg|gif|png$/,
    use:[{
        loader:'url-loader'.options: {limit:10000When the value is smaller than 10000bit, the encoding is performed. When the value is larger than 10000bit, the encoding is not performed}}}]Copy the code

When using urL-loader to process some resources, all resources will be encoded in base64 by default, but we can give it a limit attribute to restrict it, only when the resource is less than a certain value, when the value is not less than this value. It actually passes the resource to a file-loader for processing

What does Vuex Install do (source code)

Answer: The way vUE uses plug-ins is simply vue.use (plugin), for Vuex it is vue.use (Vuex).

  • Blog.csdn.net/qq_29582173…
  • zhuanlan.zhihu.com/p/29982815

4. Strong cache Negotiates cache

Answer: Priority: strong cache > negotiated cache

Strong Cache: cache-Control > Expires(http1.0 artifact, local time affected)

Negotiation cache: ETag file fingerprint comparison (http1.1 appears) > last-Modified Last Modified time comparison (last-Modified when the file is opened, in seconds)

  • More accurate juejin.cn/post/700178…
  • Juejin. Cn/post / 700180…

5. How to deal with the large data 2M of the address component in the e-commerce website?

Answer: My personal advice: Ask in batches and on demand. Data is cached to localStorage

6. Describe CSRF cross-domain request forgery in detail

Answer: www.jianshu.com/p/7f33f9c79…

There are three strategies to defend against CSRF attacks in the industry:

  • Validate the HTTP Referer field;
  • Add token to request address and verify;
  • Customize and validate properties in HTTP headers
Think about some
  • How does attacker website B send cross-domain requests to victim WEBSITE A. Send requests using the IMG tag
  • An attacker can also capture the token information in A request header in the form of HTTPS packets, because Tooken is available within the expiration period.

7. Vue updates the queue asynchronously

Answer: Vue executes asynchronously when updating the DOM. As long as it listens for data changes, Vue opens a queue and buffers all data changes that occur in the same event loop. If the same watcher is triggered more than once, it will only be pushed into the queue once. This removal of duplicate data while buffering is important to avoid unnecessary computation and DOM manipulation. Then, in the next event loop, “TICK,” Vue refreshes the queue and performs the actual (de-duplicated) work. Vue internally attempts to use native Promise.then, MutationObserver, and setImmediate for asynchronous queues, and setTimeout(fn, 0) instead if the execution environment does not support it.

To wait for Vue to finish updating the DOM after the data changes, use vue.nexttick (callback) immediately after the data changes. This callback will be called after the DOM update is complete

methods: {
    updateMessage: function () {
      this.message = 'Updated'
      console.log(this.$el.textContent) // => 'not updated'
      this.$nextTick(function () {
        console.log(this.$el.textContent) // => 'Updated'}}})Copy the code

Because $nextTick() returns a Promise object, you can do the same thing using the new ES2017 async/await syntax:

methods: {
    updateMessage: async function () {
      this.message = 'Updated'
      console.log(this.$el.textContent) // => 'not updated'
      await this.$nextTick()
      console.log(this.$el.textContent) // => 'Updated'}}Copy the code

8. Encapsulation of Toast plug-in in Vue. For example, how is the Toast component mounted on the Vue prototype?

The answer:

// Import components
import Toast from './Toast'

const obj = {}

/ / install method
obj.install = function(Vue) {
    // 1. Create a component constructor
    const toastConstructor = Vue.extend(Toast)

    // 2.new a component object
    const toast = new toastConstructor()

    // 3. Manually mount the component object to an element
    toast.$mount(document.createElement('div'))

    // 4. Add the mounted component object element to the body
    document.body.appendChild(toast.$el)

    // 5. Mount the component object to the prototype of Vue
    Vue.prototype.$toast = toast
}

// Expose the current plug-in
export default obj

Copy the code
  • Blog.csdn.net/qq_25346499…

Second, the com 2

tx

1. The size of the small program after packaging.

Applets have a 2m limit on size

Because the size of small programs has a 2m limit, so sometimes small programs are too large to upload, the solution is as follows;

1, look at the import of static resources, such as images, can be compressed, converted to PNG, or put backend resources, HTTPS import,

2, introduced JS package CSS package online if there are resources can be changed to network resources,

3. Introduced plug-in packages can be introduced as needed, not all.

4. Multiple functions can be encapsulated to reduce code redundancy

If it is still large after the above treatment, small program subcontracting can be considered to reduce the size of the package by subcontracting.

API to address the following developers.weixin.qq.com/miniprogram…

In app.json subpackages field declaration project subpackages structure can be subcontracted to reduce package size, subcontracting can be simple and independent subcontracting

The main difference is that the small program of independent subcontracting can run without the main package. It is worth noting that js cannot be reused across the package after subcontracting. Independent subcontracting can improve the speed of page loading, and there can be multiple independent subcontracting

2. Vue component to wechat component

  • Juejin. Cn/post / 696135…

3. What happens after entering the URL?

  • Juejin. Cn/post / 700180…

4. Why convert the DOM to a DOM tree when rendering the DOM? Why not just deal with strings.

  • zhuanlan.zhihu.com/p/394223139

The byte stream of HTML files sent from the network to the rendering engine is not directly understood by the rendering engine, so it is converted into an internal structure that the rendering engine can understand, which is DOM. DOM provides a representation of the structure of an HTML document.

DOM is the internal data structure that expresses HTML, connects Web pages to JavaScript scripts, and filters out unsafe content.

The HTML parser does not wait; it parses as much data as the network process loads.

The HTML parser does not wait for the entire document to load, but rather parses as much data as the network process loads.

5. Implementation and application scenarios of anti-shake and throttling

  • Juejin. Cn/post / 700545…

6. Http3.0 UDP protocol related

Third, 3 com

tujia

React componentDidMount (a = 0); React componentDidMount (a = 0); What is the value of a in the render function now? And change the value of A in setTimeout and print, what is that?

Answer: The first print is the initial value 0. The first render is 2. After adding the timer code to print the modified value, the render display is the modified value.

2. Which of the array methods are pure functions, and which change the original data?

2.1)It doesn’t change the original array:

  • Concat ()- joins two or more arrays and returns the result.
  • Every ()- checks whether each element of an array element matches a condition.
  • Some ()- Checks if any element in the array matches the specified condition.
  • Filter ()– Checks array elements and returns an array of all elements that match the criteria.
  • IndexOf ()- Searches for an element in an array and returns its location.
  • Join ()- Puts all the elements of the array into a single string.
  • ToString ()- converts an array to a string and returns the result.
  • LastIndexOf ()- Returns the last position of a specified string value, searched from back to front at the specified position in a string.
  • Map ()- Specifies a function that processes each element of the array and returns the processed array.
  • Slice ()– selects a portion of an array and returns a new array.
  • ValueOf ()– returns the original valueOf an array object.

2.2)The ones that change the original array are

  • Pop ()– removes the last element of the array and returns the deleted element.
  • Push ()- Adds one or more elements to the end of the array and returns the new length.
  • Shift ()– Removes and returns the first element of the array.
  • Unshift ()– Adds one or more elements to the beginning of the array and returns the new length.
  • Reverse ()– Reverses the order of the elements in the array.
  • Sort ()– Sorts the elements of the array.
  • Splice ()– Inserts, deletes, or replaces elements of an array.

2.1 arrays can behave like stacks (LIFO) and queues (FIFO)

A JavaScript array is a global object with stack and queue advantages in their own right. That is, JavaScript arrays can behave like stacks (LIFO) and queues (FIFO). This is also a great example of the operability of JavaScript arrays.

Stacks and queues are dynamic collections,

  • In the stack, the element that can be removed is the most recently inserted element. The stack implements lifO.

    By combining push() with pop(), we can achieve stack-like behavior

  • In a queue, the element that can be removed is always the one that has been in the collection for the longest time. Queues implement a first-in, first-out policy.

    Together with the Shift () and push() methods, arrays can be used just like queues. Add items to the back end of the array and remove items from the front end of the array

3. What are the considerations for AXIos encapsulation?

Answer: Default header configuration, with timeout configuration, with user authentication token configuration. With request, response configuration and error handling.

4. What if we limit business to 5 requests in the interceptor? When the sixth request comes in, you need to determine whether any of the previous five requests have been completed and push the new one forward.

Answer: my personal suggestion is to use a variable to count the number of requests made, adding num++ to the request made. Add num– to the request response callback. Then, determine the difference between num and 5 and fill in subsequent requests. Subsequent requests can be kept in an array, waiting to be sent.

But the current TCP multiplexing. Multiple TCP can be established at the same time, and each TCP can initiate multiple HTTP requests. There will be no such demand.

5. Browser concurrency enhancement, http2 multiplexing. Multiple TCP connections can be established, and each TCP can make multiple HTTP requests.

Answer: juejin. Cn/post / 700180…

6. For Tujia, RN is mainly used to embed in multiple APP cases.

7. REACT differs from VUE Diff

7.1)Similarities:

The DIff algorithms of Vue and React do not make cross-level comparisons, but only peer comparisons.

7.2)Difference:

1. When Vue diff, call the patch patching function and patch the real DOM while comparing

2.Vue compares nodes. When nodes have the same element type but different classnames, they are considered to be of different types and deleted

(1) Vue list comparison, using the way from both ends to the middle, the old set and the two ends of the new set have two Pointers, two pairs of comparison, if matched according to the new set to adjust the old set, after each comparison, the pointer moves to the middle of the queue;

React compares elements from left to right using index and lastIndex. If index < lastIndex, move the element. Delete and add the element according to the rules.

(3) When a set moves the last node to the front, React moves the first node backward, while Vue only moves the last node to the front. The diff performance of Vue is higher than react

8. Let var const internal implementation difference

  • Using the difference between review: www.cnblogs.com/zhaoxiaoyin…
  • ES6 Var, let, const difference and implementation principle
  1. Var declares variables with variable promotion, let and const do not
  2. Let and const declarations form a block scope; var does not
  3. Let and const cannot declare variables of the same name in the same scope, whereas var does
  4. Let, const have temporary dead zone

How it works: Var preallocates memory space, but nothing else. Const note:

Const declares a compound constant that stores a reference address. It is the address that is not allowed to change. The object itself is mutable. Const If you declare data of compound type, you can modify its properties

9. Write a topic

Promise.reject(1).then().catch((e) = > {
    return e
}).then((data) = > {
    console.log(1, data)
}).catch((e) = > {
    console.log(2, e)
})
Copy the code

/ / more then

/ / more then

If the preceding THEN is not processed, the result will continue into the last THEN

1) Promise
var p2 = new Promise((resolve,reject) = > {
    resolve(Awesome!)}); p2.then().then().then((data) = >{console.log(data)}).catch((err) = >{console.log(err)});
/ / 666
// Promise {<fulfilled>: undefined}
Copy the code

10. Write a topic

Note: This version is only for ideas that cannot be used:


const obj = {a: {b: {c:1}},e:2};

function find(obj, str){
    let strArr  = str.split('. '); // [a,b,c]
    for(let i in obj){ // a , e
        if(obj[i] === strArr[0]) {//a
            strArr.shift();
            if(typeof obj[i] === 'object'){
                find(obj[i], str)
            }else{
                return obj[i]
            }
        }
    }
};
Copy the code

reference

  • 666-DOM Trees: How do JavaScript and CSS affect DOM tree building and rendering?

conclusion