Vue interview questions 2023

1.$route和$router的区别?

  • routes : array. Route Matching Rules

  • router: object. routing object

  • $router : object. Used to jump routes and pass parameters

  • $route : object. Used to receive routing jump parameters

1. What are the lifecycle methods of Vue?

- beforeCreate before initializing the instance (the data and methods on data, methods, computed and watch cannot be accessed in the current stage.)

- created is called after the instance is created

- beforeMount is called before the mount starts (the related render function is called for the first time)

- mounted After mounting (at the current stage, the real DOM is mounted, the data is bound two-way, and the DOM node can be accessed)

- beforeUpdate Called before data update (does not trigger re-rendering process)

- updated After the update is complete

- beforeDestory Called before the instance is destroyed

- destroyed Called after the instance is destroyed (everything indicated by the Vue instance will be unbound, and all event listeners will be removed)

- activated keep-alive exclusive, called when the component is activated

- Deactivated keep-alive exclusive, the component is destroyed is called

At which step is the asynchronous request initiated?

Asynchronous requests can be made in the hook functions created, beforeMount, and mounted, because in these three hook functions, data has already been created, and the data returned by the server can be assigned.

If the asynchronous request does not need to rely on DOM, it is recommended to call the asynchronous request in the created hook function, because calling the asynchronous request in the created hook function has the following advantages:

Can get server data faster and reduce page loading time ;


If you rely on DOM elements : you need to make a request in mounted
 

2. Combined API corresponding to the 2.x version life cycle

- beforeCreate -> use setup()

- created -> use setup()

- beforeMount -> onBeforeMount

- mounted -> onMounted

- beforeUpdate -> onBeforeUpdate

- updated -> onUpdated

- beforeDestroy -> onBeforeUnmount

- destroyed -> onUnmounted

- errorCaptured -> onErrorCaptured

3. Why data is a function

The data of the component is written as a function, and the data is defined in the form of the function return value

In this way, every time a component is reused , a new piece of data will be returned, which is similar to creating a private data space for each component instance, allowing each component instance to maintain its own data .

However, simply writing it in the form of an object will make all component instances share a piece of data , which will result in a result that everything will change if it changes.
 

- Avoid data reference relationship when components are reused .
- There may be multiple instances of the vue component. If you use the object form, it will cause multiple components to share the same data, so that one component affects other components.
- If it is defined with a function, it will return a brand new object, avoiding the interaction of data between components.

4. [almost must ask] vue component pass value

- props and $emit.

        The data passed from the parent component to the child component is passed through props.

        The child component is passed to the parent component by triggering an event through $emit .

- $parent and $children get the parent component of the single sign component and the child components of the current component.

- $refs gets the component instance

- From father to son: provide and inject

- vuex state management (data sharing between different components)

--------------------------------------------

father to son

1. The child component props defines the variable
2. The parent component passes the value to the props variable through the inline attribute when using the child component

Features: One-way data flow

child's father

1. Subcomponent: $emit triggers the parent's event

2. The parent is using the component to use @custom event name = parent's method (the child brings the value out)

Features: event monitoring

non-parent-child component

vuex

4. Vue's single-item data flow

- Data is always passed from the parent component to the child component. The child component has no right to modify the data passed from the parent component, and can only request the parent component to modify the original data.

5. The difference between computed and watch and the application scenarios.

- computed is a computed attribute that relies on other attributes to calculate values, and the value of computed is cacheable, and the content will be returned only when the computed value changes.

- watch is called when the value changes.

Computed attributes are generally used in template rendering, where a value depends on other response objects or even computed attributes;

The listening attribute is suitable for observing the change of a certain value to complete a complex business logic.

6. Vuex

- Vuex can realize state sharing between different components

- vuex can achieve data persistence in components

Why do you need vuex
? Because the component only maintains its own state (data), when the component is created or when the route is switched, the component will be initialized, which will cause the data to be destroyed.
How to use
Introduce store in main.js and inject. The state that is only used for reading is concentrated in the store, and the way to change the state is to submit
mutations, which is a synchronous thing, and asynchronous logic should be encapsulated in the action.

In what scenarios will vuex be used

If it is a small application of vue, then there is no need to use vuex, and using vuex at this time will bring a burden instead. The state transfer between components can be transferred using props and custom events. But if it involves a large-scale application of vue , then a state machine with centralized management state like vuex is needed to manage the state of all components. For example, login status, adding to shopping cart, music playback, etc. In short, as long as it is a large-scale application of Vue, it is recommended to use vuex to manage the status of all components
 

- The core concept of vuex

(1), state: set the initial value

(2), getter: allows components to get data from state

(3), Mutation: the method to modify the state in the state, and must be a synchronous function

(4), Action: used to submit mutation, can contain any asynchronous request

(5)、Module

- vuex process

In the vue component, the actions to submit the modified data are triggered by dispatch.

Then trigger mutations to modify the data through the commit of actions, and mutations will receive the request of commit

The state is automatically modified through mutate, and finally the store triggers the update of each component that calls it.

7. Performance optimization of Vue

- Do not put data that does not require responsiveness in data

- v-if and v-show distinguish usage scenarios

- computed and watch are used in different scenarios

- v-for traversal must add a key, the key is preferably an id value, and avoid using v-if at the same time

- Long lists scroll to viewable area to load

- Prevent internal leaks, destroy global variables and time after component destruction

- Image lazy loading

- Routing lazy loading

- SPA pages use keep-alive cache components

- The key is guaranteed to be unique

- On-demand loading of third-party modules

- Appropriate use of keep-alive cache components

- Anti-shake, throttling

- Improve loading user experience

- Skeleton screen

----

- pre-rendered

- Server side rendering SSR

----

- compressed code

- Use cdn to load third-party modules

8. Reasons, solutions, and how to solve the white screen problem for the slow loading of the vue first screen

- The reason for the slow loading of the first screen: the first loading page has a lot of component data that needs to be rendered

- solution:

(1) Routing lazy loading

(2) UI components are loaded on demand

(3) gzip load on demand

- Solve the white screen:

(1) Use v-text to render data

(2) Use the { {}} syntax to render data, and use the v-cloak instruction at the same time

9. How to solve the slow loading speed of the first screen of SPA?

- Reasons for slow loading

1. Network delay problem

2. Is the resource file size too large?

3. Whether the resource has repeatedly sent requests to load

4. When loading the script, the rendering content is blocked

- Several common SPA first screen optimization methods

1. Reduce the size of the entry file

2. Local cache of static resources

3. The UI framework is loaded on demand

4. Compression of image resources

5. Repeated packaging of components

6. Enable GZip compression

7. Use SSR

10. Talk about your understanding of spa single page

- spa only loads html, js, css when the web page is initialized

- Once the page is loaded, the page will not be reloaded and rendered due to user actions

- The change of the page is to use the routing mechanism to realize the transformation of the html content, avoiding the reloading of the page

11. Why does vue use asynchronous rendering

- Vue is a component-level update. If the data in the current component changes, it will update the component.

When the data is changed once, the component needs to be re-rendered. The performance is not high. In order to prevent the component from being updated as soon as the data is updated, an asynchronous update rendering is made.

- (The core method is nextTick)

12. Which hooks will be triggered on the first page load?

- The beforeCreate, created, beforeMount, mounted hooks will be triggered when the page is loaded for the first time

13. The execution sequence of Vue's parent-child component life cycle hook function

Load rendering process
parent beforeCreate -> parent created -> parent beforeMount -> child beforeCreate -> child created
-> child beforeMount -> child mounted -> parent mounted
child component update process
parent beforeUpdate -> child beforeUpdate -> child updated -> parent updated
parent component update process
parent beforeUpdate -> parent updated
destruction process parent beforeDestroy -> child beforeDestroy -> child destroyed -> parent destroyed
Summary : the parent component starts first and the child component ends first
 

14. What is vue-router dynamic routing? What is the problem.

We often need to map all routes matched by a certain pattern to the same component. For example, we have a
User component that is rendered for all users with different IDs. Then, we can use "dynamic path parameters" (dynamic segment) in the routing path of vue-router to achieve this effect:
 

 const User = {
   template: "User", 
 };
 const router = new VueRouter({
   routes: [
      // 动态路径参数 以冒号开头
      { path: "/user/:id", component: User },
   ],

Question  :  What should I do if the reuse of vue-router  components causes the routing parameters to fail?

Solution  :

1. Listen to the routing parameters through watch and send the request again

 watch:{
   "router":function(){
      this.getData(this.$router.params.xxx)
    }
  }

2. Use  : key  to prevent multiplexing

router-view   :key="$route.fullPath"

15. How to solve the data loss when the Vuex page is refreshed?

Need to do  vuex data persistence  , generally use local storage scheme to save data,

16. Routing parameters

-使用router-link时
    query传参:<router-link :to="/xxx/xxx?id=xx&name=xxx"></router-link>
    <router-link :to="{
        path:'/xxx/xx',
        query:{
            id:xxx,
            name:xxx
        }
    }">跳转</router-link>
    使用this.$route.query.id获取
    params传参
    <router-link :to="/xxx/xxx/001/sddf"></router-link>
    <router-link :to="{
        name:'asd',
        params:{
            id:xxx,
            name:xxx
        }
    }"></router-link>
    -router.js
    {
        name:'asd',
        path:'xxxx/:id/:name',
        component:Detail
    }
    Receive parameter this.$route.params.id
- When using params to pass parameters, if it is written as an object, you need to configure the name attribute of the response in router.js, and it needs to occupy a place.
- Use programmatic routing to navigate
    this.$router.push({         name:'xxx',         params:{             id:xxx,             title:xxx         }     })





17. Route Guard

Router.beforeEach
: global pre-routing guard, to: target route, from: source route, next(): release; custom parameters need to be configured in the routing meta information (meta) to control permissions .
router.afterEach(): Global post-routing guard, which can be used to dynamically change the page title.
beforeEnter(): Single route configuration, route exclusive guard, and permission setting for a certain route.
beforeRouteEnter(): The built-in guard of the component is called before entering the component through routing rules.
beforeRouteLeave(): The built-in guard of the component is called before leaving the component through routing rules.

18. Advantages of vue3

- Performance improvement,
    package size reduced by 41%,
    55% faster initial rendering, 133% faster update rendering,
    memory reduction 54%
- source code upgrade
    uses proxy instead of defineproperty to achieve responsive
    rewriting of virtual dom implementation and elimination of redundant code (tree-shaking)
-vue3 Can better support typescript
- new feature
    composition API (composition api)
        setup configuration
        ref and reactive
    new built-in component
        fragment
        teleport
    new lifecycle hook
    remove keycode support as v-on modifier
    data is always a function

19. The difference between the watchEffect function and computed

  1. -computed: It is a calculation function, focusing on the calculated value, so the return value must be written

  2. -watchEffect: It is a monitoring function, focusing on the process, without writing the return value

20. [almost must ask] the role of key value in Vue

1. When vue is rendering, it will first compare the new DOM with the old DOM. If the dom structure is consistent, vue will reuse the old dom. (At this time, data rendering may be abnormal)

2. Use key to add a unique identifier to dom, let vue force update dom

[The function of key value in vue verbatim draft]

       Hello interviewer, this is how I understand the key value. The main function of the key value is to add a unique identifier to the element to improve the rendering performance of vue. When the data changes, vue will use the diff algorithm to compare the old and new virtual DOM. If the key value is the same, the reuse element will be considered. If the key value is different, the element will be forced to be updated. Generally, the element key is set as id to ensure that vue can maximize the reuse of the same key value when updating data. Elements.
 

Why does the v-for loop have to bind the key?

Add a key to each dom element as a unique identifier , and the diff algorithm can correctly identify this node , making page rendering faster !


21. What are the commonly used methods of arrays? Which methods will change the original array and which will not

Will change the original array:

pop (remove the last element of the array and return the removed element)

push ( add one or more elements to the end of the array and return the new length)

shift (delete and return the first element of the array)

unshift (add one or more elements to the beginning of the array and return the new length)

reverse (reverse the order of the elements of the array)

sort (sorts the elements of an array)

splice (for inserting, deleting, or replacing elements of an array)

Does not change the original array:

concat --- concatenates two or more arrays and returns the result.

every --- checks whether each element of the array element meets the condition.

some --- check whether there is an element in the array element that meets the specified condition.

filter --- Detect array elements and return an array of all elements that meet the criteria.

indexOf --- Searches for an element in the array and returns its position.

join --- put all the elements of the array into a string.

toString---Convert the array to a string and return the result.

lastIndexOf---Returns the last occurrence position of a specified string value, searching from the back to the front in a specified position in a string.

map---Process each element of the array through the specified function and return the processed array.

slice --- Select a part of the array and return a new array.

valueOf---Returns the original value of the array object
 

22. What is the prototype chain?

Each instance object has a proto attribute, which points to the prototype object of the constructor. The prototype object of the constructor is also an object and also has a proto attribute. In this way, the process of looking up layer by layer forms a prototype chain .

23. What is a closure? What are the pros and cons of closures?

  •  Concept: function nested function, internal variable can access external variable, this variable is called free variable
  •  Problem Solved: Saving Variables
  •  The problem: it will cause memory leaks
  •  Closure application: anti-shake throttling

24. What are the new features of es6?

  • template string
  • arrow function
  • for-of (for iterating over data—such as values ​​in an array.)
  • ES6 incorporates Promise objects into the specification and provides native Promise objects.
  • Added let and const commands for declaring variables .
  • There is also the concept of introducing the module module

25. What are the common methods of vertically centering boxes? Please give 3 examples?

Realize by using the positioning method of son and father

    <style>
        .container{
            width: 300px;
            height: 300px;
            position: relative;
        }
        .conter{
            width: 100px;
            height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -50px;
            margin-left: -50px;
        }
    </style>

Using the transform of Css3 , you can easily realize the vertical centering of the element when the height and width of the element are unknown .

   <style>
        .container{
            position: relative;
        }
        .conter{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
    </style>

flex

   <style>
        .container{
         display: flex;
         justify-content: center;
         align-items: center;
        }
        .conter{
            
        }
    </style>

26. What are the js data types and what is the difference

  • Basic types: string, number, boolean, null, undefined, symbol, bigInt
  • Reference type: object, array
  • Basic types are stored in the stack , with small space and frequent operations
  • The reference data type is stored in the heap , and its address is in the stack . Generally, our access is its address

27. What is the Same Origin Policy

The so-called same-origin policy is a security mechanism of the browser to restrict communication between websites of different origins (the same domain name, protocol, and port number)

28. What is promise and what is its function

  • Promise is an object that can get asynchronous operation information from changing objects
  • He can solve the problem of callback hell , that is, the problem of asynchronous deep nesting

29. What is the difference between let and const

  • The let command does not have variable promotion , if it is used before let, it will cause an error
  • If there are let and const commands in the block area, it will form a closed scope
  • Duplicate statement not allowed
  • const defines constants and cannot be modified, but if an object is defined , the data inside the object can be modified

30. The difference between == and ===

  • == is not strictly equal
    • equal in value
  • === is strictly equal, and compares the data types and value sizes on both sides
    • The value and the reference address are both equal to be equal

31. What is anti-shake and throttling, how does js deal with anti-shake and throttling

  • First of all, anti-shake is to stop the previous event when the next event is triggered

  • Throttling is to trigger the current event after the end of the previous event

  • By setting the throttle ( timer )

32. Cross domain

Cross-domain reasons: browsers protect resources for security reasons, same-origin policy . ( protocol, domain name, port number )
to solve cross-domain:
jsonP but can only use the get principle - set the requested interface to the src attribute of the script tag and pass a function to the background to achieve cross-domain. The background response is a function call
cors: the most commonly used.
Reverse proxy: The local front-end sends to the local back-end without cross-domain, (same origin) the local back-end forwards to other servers after receiving the request (there will be no cross-domain between the server and the server). The proxy requires a special flag in the path .
 

33.

Guess you like

Origin blog.csdn.net/admin12345671/article/details/130052025