Brief review (vue + js)

1. The difference between forEach and for loop

forEach has no return value, cannot be interrupted, does not support adding and deleting operations in the loop, only suitable for collection or array traversal

2. Flexibility and layout

1. Realization: The parent element is a flexible box with three child elements inside. Set the horizontal alignment of the child elements, and the first element occupies 20%, the second element occupies 30%, and the third element occupies the remaining space

Horizontal alignment: flex-direction:row
setting proportion: the first element flex: 2; the second element flex: 3; the third element flex: 5

2, talk about the collection of three attributes of flex

flex-grow: set or retrieve the expansion ratio of the flex box

让第二个元素的宽度为其他元素的三倍:
div:nth-of-type(1) {flex-grow: 1;}
div:nth-of-type(2) {flex-grow: 3;}
div:nth-of-type(3) {flex-grow: 1;}

flex-basis: set or retrieve the elastic box scaling benchmark value

设置第二个弹性盒元素的初始长度为 80 像素:
div:nth-of-type(2) {flex-basis: 80px;}

flex-basis: Set the shrinkage ratio of the elastic box.
Calculation: self-width-overflow value flex-shrink value self-width/total weight value
total weight = sub-element flex-shrink value * self-width sum

3. Data type and depth copy

1. How to judge whether it is a deep copy or a shallow copy?
2. How to make a deep copy?
3. What are the two types of data? What are included?
4. How are these two data types stored in the stack?
Reference link: https://www.cnblogs.com/echolun/p/7889848.html

4. Map and set in es6

1. set: Array de-duplication, is a set of keys, but does not store value. Since the key cannot be repeated, there is no repeated key in the Set.
2. Map: The structure of a set of key-value pairs has extremely fast search speed. Solved the problem that JavaScript can only use strings as keys

5. The difference between module import and export in es6 and node

  • es6
    import: import module name from ""
    Export: use export default and export to expose members to the outside
    [Note 1] : The members exposed by export can only be received by {}. This form is called
    simultaneous export on demand If some members are not needed when importing, they can not be defined in {}
    [Note 2] : The members exported by export must be received by {} in strict accordance with the export name.
    If you have to alias the exported non-default module, use as to alias
  • node
    import: use var name = require('module identifier') to import
    Export: use module.export and exports to expose members

6. Jump to routing in vue and pass parameters params and query

  • <router-link to = "路径">
  • this.$ router.push(): commonly used to pass parameters
  1. Query import method: params can only use name to import routes, and query should use path to import
       created(){  //生命周期里接收参数
            this.id = this.$route.query.id,  //接受参数关键代码 【注意!!!】接受的时候是 **route**!!!
            console.log(this.id)  
      }
  1. Query transmission method: similar to the get parameter in our ajax, the parameters are displayed in the browser address bar, and params are similar to post, and the parameters are not displayed in the browser address bar
       this.$router.push({  //核心语句    
           path:'/select',   //跳转的路径
           query:{           //路由传参时push和query搭配使用 ,作用时传递参数
           id:this.id , 
           }
        })
  • this.$router.replace{path:'/'} [similar to the second one]
  • Params is a part of routing and must be present. The query is a parameter spliced ​​after the url, it doesn't matter if it doesn't.
    Once params is set in the route, params is a part of the route. If the route has params to pass parameters, but this parameter is not passed during the jump, the jump will fail or the page will have no content.

7. What is the difference between vuex, localstorage and sessionstorage? Cookie size and characteristics

  • the difference:
  1. Vuex is stored in memory, localstorage (local storage) is stored locally as a file for permanent storage, sessionstorage (session storage) is temporarily stored.
  2. LocalStorage and sessionStorage can only store string types. For complex objects, you can use stringify and parse of the JSON object provided by ECMAScript to process
  • Application scenario: vuex is used to transfer values ​​between components, localstorage and sessionstorage are mainly used to transfer values ​​between different pages.

  • Permanence: When the page is refreshed (the refresh page here refers to --> F5 refresh, which belongs to clear memory), the value stored by vuex will be lost, and the sessionstorage page will be cleared after it is closed, but localstorage will not.
    [Note]: For unchanged data, localstorage can be used instead of vuex, but when two components share a data source (object or array), if one of the components changes the data source, and the other component is expected to respond to the change , Localstorage, sessionstorage cannot be done, the reason is the difference 1.

  • cookie: will be sent to the server along with http

  1. There is a size limit, 4kb
  2. Quantity limit: 50
  3. Session-level storage, cleared as the page is closed
  4. Cookie can span multiple web pages under the same domain name, but cannot span multiple domain names! Use
  5. Usage scenarios: (1) save the user login status; (2) track user behavior; (3) customize the page; (4) create a shopping cart... etc.

8. Five core attributes of vuex

https://www.cnblogs.com/y896926473/p/6709733.html

  • What is vuex?
    Vuex is a state management mode developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application and uses corresponding rules to ensure that the state changes in a predictable manner.
    The core of every Vuex application is the store. "Store" is basically a container, which contains most of the state of your application.
  • Core attributes
  1. state => basic data
  2. getters => data derived from basic data, getters receive state as its first parameter, and other getters as the second parameter. If not needed, the second parameter can be omitted as shown in the following example:
  3. mutations => The method of submitting the changed data, synchronization! Asynchronous requires the use of action;
    each mutation has a string event type (type) and a callback function (handler). This callback function is where we actually make state changes, and it will accept state as the first parameter and submit the payload as the second parameter. (The submitted load should be an object in most cases), and the submitted load can also be omitted.
  4. actions => like a decorator, wrapping mutations so that they can be asynchronous. Action is similar to mutation, but the difference is:
    actioan submits the mutation instead of directly changing the state.
    action can contain any asynchronous operation
  5. modules => Modular Vuex

9. Pass value of vue parent and child components

  • Father to son
  1. The parent component passes the value to the child component 1 The
    parent component adds a custom attribute where the child component is called. The value of the attribute is the value that needs to be passed to the child component. If the value to be passed is a variable, or a boolean, or It is a number type and needs to use binding properties.
    In the place where the subcomponent is defined, add an option props. The value of mode one props is an array, and the element is a custom property name.
    You can get it in the subcomponent through a custom property name Data passed to the parent component
  2. The parent component passes the value to the child component. 2
    In the place where the child component is defined, add an option props. In the second method, the value of props is an object. The key is a custom property name, and the value is a data type.
    Teamwork improves the rigor of the code. If the type is incorrect , There will be a warning message, but it will not prevent the rendering of your code
  3. The parent component passes the value to the child component. 3
    In the place where the child component is defined, add an option props. Method 3 The value of props is an object, the key is a custom property name, and the value is an object. The keys of this object are type and respectively default, indicates the data type and default value. If the data type is an object or an array, the default value must be a function, and the rest are directly assigned
  • Parent component sub-assemblies to pass the value of
    the local parent component calls subcomponents, which is bound to a custom event, the event is performed by the parent component, remember not to add ()
    places in the sub-components defined in need Inside the pass-by function, execute this.$emit('customized event name','passed value')
    to pass the value of the component, and it needs to conform to a one-way data flow-parent to child pass-if the component needs child to parent Pass, you need to consider carefully
  • The method of the child component calling the parent component: this.$parent.event

10. Jitter and throttling

  • Scenario: resize/scroll triggers statistical events, mousemove events when dragging, etc.
  • Function anti-shake: After a function has been executed once, it cannot be executed again within a certain period of time; if this function is triggered within the waiting time, the waiting time will be recalculated.
    By calling debounce ([dɪ'baʊns] the enemy is dead), a closure function is returned.
    Package:
<script>
    var n = 0;
    function debounce (method, wait, flag) {
        var timer = null;
        var context, args, result, timestamp;
        var later = function () {
            var oDate = new Date();
            var last = oDate.getTime() - timestamp; // 计算第一次时间戳与当前时间戳的差值。
            if (last < wait && last >= 0 ) { // 在等待时间内触发此函数,重新计时。
                timer = setTimeout(later, wait - last);
            } else {
                timer = null;
                if (!flag) { // 限制flag 为true时,执行回调函数。
                    result = method.apply(context, args);
                    if (!timer) {
                        context = args = null
                    }
                }
            }
        }

        return function () {
            var oDate = new Date();
            var callNow = flag && !timer; // 代表第一次调用立即执行。

            timestamp = oDate.getTime(); // 记录下当前时间戳
            context = this;
            args = arguments;
            if (!timer) { // 第一次触发时,timer为空,进入此分支
                timer = setTimeout(later, wait);
            }
            if (callNow) { // 第一次触发且flag为true,进入此分支
                result = method.apply(context, args);
                context = args = null
            }
            return result;
        }
    }
    window.onscroll = debounce (function () {
        console.log(1)
    }, 500, false)
</script>
 flag为true时,连续事件触发时,只会在第一次触发的时候执行回调。
 flag为false时,连续事件触发时,只会在最后一次触发的时候执行回调。
  • Throttling: When the event is triggered continuously, it is guaranteed to call the event processing function only once within a certain period of time. The interpretation of economical customs is like our faucet releases water. As soon as the valve is opened, the water pours down. Upholding the fine traditional virtues of diligence and thrift, we must turn the faucet down. Drop by drop in the time interval.
    Implementation method : timestamp and timer
<script>
    var n = 0;
    function resizeHandler () {
        console.log(n++)
    }
    function throttle (method, context) {
        clearTimeout(method.timer)
        method.timer= setTimeout(function () {
            method.call(context)
        }, 500)
    }
    window.onresize = function () {
        throttle(resizeHandler, window)
    }
</script>

11. When using flex layout in mobile projects, what compatibility issues have you encountered during testing? How to solve it? (During the test, due to different mobile phone models and different adaptations, some compatibility problems and solutions will occur)

https://blog.csdn.net/hzxOnlineOk/article/details/87858281

12. Cross-domain issues

Solution to cross-domain: jsonp cross-domain, cross-domain resource sharing (cors), nodejs middleware proxy cross-domain, nginx reverse proxy
Vue: use node + webpack + webpack-dev-server, in the development environment, due to vue rendering The service and the interface proxy service are both the same webpack-dev-server, so the page and the proxy interface are not cross-domain.
jsonp principle: dynamically create script tags, and then request a URL with parameters to achieve cross-domain peering

  1. Native implementation:
 <script>
  var script = document.createElement('script');
  script.type = 'text/javascript';

  // 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
  script.src = 'http://www.daxihong.com:8080/login?user=admin&callback=jsonCallback';
  document.head.appendChild(script);

  // 回调执行函数
  function jsonCallback(res) {
      alert(JSON.stringify(res));
  }
 </script>
 服务器端返回如下(返回即执行全局函数)
 jsonCallback({"status": 0, "user": "admin"})
  1. jquery implementation
$.ajax({
  url: 'http://www.domain2.com:8080/login',
  type: 'get',
  dataType: 'jsonp',  // 请求方式为jsonp
  jsonpCallback: "handleCallback",    // 自定义回调函数名
  data: {}
})

13. Vue two-way binding principle

Vue.js uses data hijacking combined with the publisher-subscriber model to hijack the setter and getter of each property through Object.defineProperty(), publish messages to subscribers when data changes, and trigger corresponding listener callbacks.

14. Callback function

Can be used as a parameter and called by other functions

  • Asynchronous callback: Specify a function when an asynchronous task is initiated, and this function will be called automatically when the asynchronous task is completed.
  • Why asynchronous callbacks?
    Need to get asynchronous task execution results, but it should not be allowed to clog (lower efficiency), that want to obtain efficient execution results of the task. Previously, when using the thread pool or process pool to submit a task, if you want to process the execution result of the task, you must call the result function or the shutdown function, and they are all blocking, and will wait until the task is executed before it can continue. In this waiting process, other tasks cannot be executed, which reduces efficiency. Therefore, a solution is needed to ensure that the thread that parses the result does not have to wait, and to ensure that the data can be parsed in time. This solution is an asynchronous callback.
  • Commonly used: ajax, axios request asynchronous callback

15. Closure

  • Concept: A closure is a function that can read the internal variables of other functions . Since the sub-functions inside the function can read local variables, the closure can be simply understood as "a function defined in a function" (then return this internal function).
    So, in essence, a closure is a bridge connecting the inside of the function and the outside of the function.
  • Features:
  1. Closure reads the internal variables of the function
  2. Keep the values ​​of these variables in memory at all times. Will not be cleared after the function call
  • Disadvantage
  1. Because writing variables always exist in memory, it will cause excessive memory consumption and affect performance
  2. Cause a memory leak.
  • [Note] Closure can make the value inside the function can be modified outside the function. So, if you use the parent function as an object, the closure as its public method, and the internal variable as its private value, you must be careful at this time. Change the value of the internal variable of the parent function at will.

16, the two cores of vue.js

Data-driven and component system

17. Optimization of front-end page performance

  • The CSS is placed at the top of the page (in the head tag), and the JS file is placed at the bottom of the page. The
    browser will render the entire page after downloading all the CSS. Therefore, the best practice is to put the CSS at the top of the page (yes Put CSS in the head), let the browser download CSS as soon as possible.
    The js file is the opposite. The browser executes immediately after loading js, which may block the entire page and cause the page to display slowly, so js is best placed at the bottom of the page. However, if the js file is needed for page parsing, it is not appropriate to put it at the bottom.
  • Set as few global variables as possible.
  • Minimize DOM manipulation
  • Don't set styles in tags, it is best to externally quote CSS files.
  • Reduce http requests and set up HTTP caching reasonably; (the most effective way)
    [Reason] The http protocol is a stateless application layer protocol, which means that each http request needs to establish a communication link and perform data transmission. On the server side, Each http needs to start an independent thread to process. These communications and services are expensive. Reducing the number of http requests can effectively improve access performance.
  1. The main means to reduce http is to merge CSS, merge js, merge pictures (multiple pictures are merged into one).
  2. Set up HTTP caching: The power of caching is powerful, and proper caching settings can greatly reduce HTTP requests.
  3. If possible, merge external scripts and styles as much as possible, and merge multiple into one. In addition, CSS, Javascript, and Image can all be compressed with corresponding tools, which can often save a lot of space after compression.
  • Using browser caching
    For a website, the update frequency of static resource files such as CSS, js, logo, and icons is relatively low, and these files are almost required for every http request. If these files are cached in the browser , Can improve performance extremely. By setting the attributes of cache-control and expires in the http header, the browser cache can be set. The cache time can be several days or even months.
  • If you encounter a large file, you can place the file in a timer and use asynchronous operations to wait for other files to load before loading the file in the timer.
  • CSS Sprites: merge CSS images
  • Lazy loading of images
    This strategy may not actually reduce the number of HTTP requests, but it can reduce the number of HTTP requests under certain conditions or when the page is just loaded. For pictures, when the page is first loaded, only the first screen can be loaded, and subsequent pictures are loaded when the user continues to scroll back.
  • Reduce cookie transmission and try to use localStorage to store local data.
    On the one hand, cookies are included in each request and response. A cookie that is too large will seriously affect data transmission. Therefore, which data needs to be written into the cookie should be carefully considered, and minimize the amount of data transmitted in the cookie. The amount of data.
  • Compress Image.
  • 18. How to interrupt the forEach loop

Use try...catch to terminate the loop

let arr = [1, 2, 3]
try {
	arr.forEach(item => {
		if (item === 2) {
			throw('循环终止')
		}
		console.log(item)
	})
} catch(e) {
	console.log('e: ', e)
}

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-uMUrZYNr-1575273502332)(en-resource://database/1648:0)]

19. Determine whether a data exists in the array?

  • javascript的indexOf()method
    var arr_data = [1,2,3];
    arr_data.indexOf(1); //如果存在返回值的下标,不存在返回-1

  • jquery的$.inArray()method
    $.inArray(1, arr_data); //如果存在返回值的下标,不存在返回-1

  • arr.find()
    The find() of an array instance is used to find the first array element that meets the conditions. Its parameter is a callback function. All the array elements traverse the callback function in turn until the first element with a return value of true is found, and then the element is returned, otherwise it returns undefined.
    Note: The find() function will not execute for empty arrays. find() did not change the original value of the array

   arr.find(function(value) { 
      if(value === 要查找的值) { 
          //则包含该元素    
   }})
  • arr.findIndex()Returns the position of the first array element that meets the condition, if all elements do not meet the condition, returns -1.

Note: find(), findIndex() make up for the lack of index: (that is, judge NAN)

    [NaN].indexOf(NaN) // -1
    [NaN].findIndex(y => Object.is(NaN, y))// 0
  • for loop and if judgment

20. Array beats flat

Example:var arr = [1,2,[3,4,5,[6,7,8],9],10,[11,12]]

  1. Recursive implementation:
function fn(arr){
    let arr1 = []
     arr.forEach((val)=>{
         if(val instanceof Array){
             arr1 = arr1.concat(fn(val))
         }else{
             arr1.push(val)
         }
      })
      return arr1
 }
  1. reduce implementation
function fn(arr){
    return arr.reduce((prev,cur)=>{
        return prev.concat(Array.isArray(cur)?fn(cur):cur)
    },[])
}
  1. flat
arr.flat(Infinity)
  1. Spread operator
function fn(arr){
    let arr1 = [];
    let bStop = true;
    arr.forEach((val)=>{
        if(Array.isArray(val)){
            arr1.push(...val);
            bStop = false
        }else{
            arr1.push(val)
        }
    })
    if(bStop){
        return arr1;
    }
    return fn(arr1)
}
let arr1 = arr.toString().split(',').map((val)=>{
           return parseInt(val)
       })
       console.log(arr1)
  1. apply
function flatten(arr){
    while(arr.some(item => Array.isArray(item))){
          arr =  [].concat.apply([],arr);
    }
     return arr;
}

Guess you like

Origin blog.csdn.net/BookstoreSpirit/article/details/103296869