Some questions of vue

Some questions of vue

1. Under what circumstances should I use Vuex?

  • If the application is simple enough, it is best not to use
    Vuex
    ,A simple
    store
    Mode
  • When you need to build a medium and large single-page application, use
    Vuex
    Can better manage state outside of the component

2. What is the difference between Vuex and pure global objects?

  • Vuex
    The state storage is responsive. when
    Vue
    Component from
    store
    When reading the status, if
    store
    If the status in the system changes, the corresponding components will be updated efficiently accordingly.
  • Cannot be changed directly
    store
    In the state. change
    store
    The only way to state in is to explicitly commit
    (commit) mutation
    . This allows us to easily track the changes of each state, so that we can implement some tools to help us better understand our applications.

3. Why can't asynchronous operation be done in the mutation of Vuex?

  • Vuex
    The only way for all status updates in
    mutation
    , The asynchronous operation is passed
    Action
    To submit
    mutation
    Realization, so that we can easily track the changes of each state, so that we can implement some tools to help us better understand our applications.
  • Each
    mutation
    After the execution is completed, it will correspond to a new state change, so
    devtools
    You can take a snapshot and save it, and then you can achieve it
    time-travel
    Up. in case
    mutation
    Supporting asynchronous operation, there is no way to know when the state is updated, and the state cannot be tracked well, which brings difficulties to debugging.

4. Does vuex's action have a return value? What is returned?

  • store.dispatch
    Can handle triggered
    action
    The processing function returns
    Promise
    ,and
    store.dispatch
    Still return
    Promise
  • Action
    Usually asynchronous, you have to know
    action
    When will it end or combine multiple
    action
    To handle more complex asynchronous processes, you can define
    action
    When returning a
    promise
    Object, you can distribute
    action
    Can be returned by processing
    Promise
    Handling asynchronous processes

One

store.dispatch
Multiple triggers in different modules
action
function. In this case, only when all trigger functions are completed, the returned
Promise
Will be executed.

5. What is the difference between computed and watch and used scenarios?

  • computed
    : Is a calculated attribute, depends on the value of other attributes, and
    computed
    The value of is cached, only the attribute value it depends on changes, the next time it is obtained
    computed
    Will be recalculated when the value of
    computed
    The value of

  • watch
    : There is no caching, and it is more of an "observation" function. It is similar to the monitoring callback of some data. When the monitored data changes, the callback will be executed for subsequent operations; when we need to monitor the properties of the object in depth, we can turn on
    deep: true
    Option, so that every item in the object will be monitored

  • Application scenarios:

    • When we need to perform numerical calculations and rely on other data, we should use
      computed
      , Because you can use
      computed
      The caching feature of to avoid recalculation every time the value is obtained;
    • When we need to perform asynchronous or expensive operations when the data changes, we should use
      watch
      ,use
      watch
      Options allow us to perform asynchronous operations (access to an API), limit how often we perform the operation, and set intermediate states before we get the final result. These are things that calculated properties cannot do.

6. What are the communication methods of Vue2.x components?

  • Parent-child component communication

    • Event mechanism (**parent->child props, child->parent $on, $emit)
    • Get parent-child component instance $parent, $children
    • Ref calls the properties or methods of the component by obtaining the instance
    • Provide, inject (not recommended, very commonly used in component libraries)
  • Brother component communication

Vue.prototype.$bus = new Vue

-Vuex -eventBus This method uses an empty Vue instance as the central event bus (event center), which can be used to trigger events and monitor events, so as to achieve communication between any components, including parent-child, intergenerational, and sibling components Copy code
  • Cross-level component communication

    • Vuex
    • $attrs, $listeners
    • Provide, inject

7. Why v-for and v-if are not recommended to be used together

  • when
    v-for
    with
    v-if
    At the same node,
    v-for
    Priority ratio
    v-if
    Higher, which means
    v-if
    Will be repeated separately for each
    v-for
    In the loop. If the array to be traversed is very large, and the data to be displayed is very small, this will cause a lot of performance waste
  • Recommended for this scenario
    computed
    To filter the data first

8. Why is the data in the component a function?

  • If a component is reused multiple times, multiple instances will be created. Essentially, these instances all use the same constructor.
  • in case
    data
    If it is an object, the object belongs to a reference type, which will affect all instances. So in order to ensure that the components of different instances
    data
    Do not conflict,
    data
    Must be a function.

9. Why can't the child component modify the Prop passed by the parent component?/How to understand the one-way data flow of vue?

  • Vue
    Advocate one-way data flow, that is, the updates of the parent props will flow to the child components, but the reverse will not work.
  • This is to prevent accidentally changing the state of the parent component, making the data flow of the application difficult to understand.
  • If the one-way data flow is destroyed, when the application is complex,
    debug
    The cost will be very high.

10. How does v-model realize two-way binding?

  • v-model
    It is used to create two-way binding on form controls or components
  • His essence is
    v-bind
    with
    v-on
    Syntactic sugar
  • Use on a component
    v-model
    , The default binding name for the component is
    value
    of
    prop
    And named
    input
    event

11. What is the realization principle of nextTick?

  • Next time
    DOM
    After the update cycle is over, the delayed callback is executed, and nextTick is used immediately after the data is modified to obtain the updated
    DOM
    .
  • nextTick
    Mainly used macro tasks and micro tasks.
  • Try to adopt according to the execution environment
    Promise, MutationObserver, setImmediate
    , Use if none of the above
    setTimeout
    Defines an asynchronous method, called multiple times
    nextTick
    The method will be stored in the queue, and the current queue will be cleared through this asynchronous method.

12. What is the principle of Vue event binding?

  • Native event binding is through
    addEventListener
    Binding to real elements, component event binding is through
    Vue custom $on
    Achieved.

13, talk about the role of virtual Dom and key attributes

  • Because of the operation in the browser

    DOM
    It is very expensive. Frequent operation
    DOM
    , Will produce certain performance problems. This is the reason for the virtual Dom.

  • Virtual DOM
    The essence is to use a native JS object to describe a DOM node. Is true
    DOM
    Layer of abstraction. (That is, in the source code
    VNode
    Class, it is defined in
    src/core/vdom/vnode.js
    in. )

  • The realization principle of virtual DOM mainly includes the following 3 parts:

    • Use JavaScript objects to simulate the real DOM tree and abstract the real DOM;
    • diff algorithm-compare the differences between two virtual DOM trees;
    • pach algorithm Apply the difference between two virtual DOM objects to the real DOM tree.
  • key is

    Vue
    in
    vnode
    The only mark through this
    key
    ,our
    diff
    Operation can be more accurate and faster

    • More accurate: because the key is not reused in place, in
      sameNode
      function
      a.key === b.key
      In the comparison, in-situ multiplexing can be avoided. So it will be more accurate.
    • Faster: Use the uniqueness of the key to generate a map object to obtain the corresponding node, which is faster than the traversal method

14. Why is it not recommended to use index as the key?

  • Not recommended
    index as the key, basically the same as if it is not written
    , Because no matter how the order of your array is reversed, the index is always 0, 1, 2 in this arrangement, causing Vue to reuse the wrong old child nodes and do a lot of extra work

15. Tell me about your understanding of the life cycle of Vue

  • beforeCreate
    : After the instance is initialized, the data observation and event configuration are not ready at this time (undefined)
  • created
    : The value of the data data is read, but the DOM has not been generated yet
  • beforeMount
    : The page has not been successfully rendered into the data in our data
  • mounted
    : Successfully rendered
  • beforeUpdate
    : Before the view is re-rendered and updated
  • updated
    : The view has been updated.
  • beforeDestroy
    : Destroy the current component
  • destroyed
    . After successful destruction, the destroyed hook will be triggered
  • keep-alive
    Has its own independent hook function activated and deactivated

16. What is the calling sequence of component life cycle in Vue?

  • The calling order of the components is first father and then child, and the order of rendering completion is first child and then father.
  • The destruction operation of the component is the parent first and then the child, and the order of completion of the destruction is the child first and then the parent.

17. At what stage can I access and manipulate the DOM?

In hook function

mounted
Before being called,
Vue
The compiled template has been mounted on the page, so in
mounted
You can access and manipulate the DOM.

18. In which life cycle is your interface request generally placed?

  • Can be in the hook function

    created, beforeMount, mounted
    Because in these three hook functions, data has been created, the data returned by the server can be assigned.

  • However, it is recommended to call asynchronous requests in the created hook function, because calling asynchronous requests in the created hook function has the following advantages:

    • The server data can be obtained faster, and the page loading time can be reduced;
    • ssr does not support beforeMount and mounted hook functions, so putting it in created helps consistency;

19. What are the implementation principles of vue routing hash mode and history mode, and what is the difference between them?

  • hash mode:

    • #The change of the hash value behind will not cause the browser to send a request to the server. If the browser does not send a request, the page will not be refreshed
    • By monitoring the hashchange event, you can know what changes have occurred in the hash, and then update part of the content of the page according to the changes in the hash.
  • history mode:

    • The realization of the history mode is mainly the two APIs published by the HTML5 standard, pushState and replaceState. These two APIs can change the URL, but will not send a request. In this way, you can monitor url changes to update part of the content of the page.
  • the difference

    • In url display, hash mode has "#", history mode does not
    • When the page is refreshed, the hash mode can be loaded to the page corresponding to the hash value normally, and if the history is not processed, a 404 will be returned. Generally, the backend needs to be configured to redirect all pages to the homepage route.
    • Compatibility, hash can support lower version browsers and IE.

20. What are the Vue-router navigation guards?

  • Global front/hook:
    beforeEach, beforeResolve, afterEach
  • Guards exclusive to routing:
    beforeEnter
  • The guard in the component:
    beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave

21. Why not use arrow functions when writing life cycle hooks or other option/properties in a Vue instance?

  • The arrow function itself is not defined
    this
    Context.
  • When you use arrow functions in Vue programs
    (=>)
    Time,
    this
    Keyword disease will not be bound to
    Vue
    Instance, so an error will be raised. Therefore, it is strongly recommended to use standard function declarations instead.

22. Tell me about your understanding of keep-alive components

  • keep-alive
    It is a built-in component of Vue, which can keep the state of contained components and avoid re-rendering. It has the following characteristics:

    • Generally used in conjunction with routing and dynamic components for caching components;
    • provide
      include
      with
      exclude
      Attributes, both support strings or regular expressions,
      include
      Indicates that only components with matching names will be cached,
      exclude
      Indicates that any component with a matching name will not be cached, where
      exclude
      Priority ratio
      include
      high;
    • Corresponding to two hook functions
      activated and deactivated
      , When the component is activated, trigger the hook function
      activated
      , When the component is removed, the hook function is triggered
      deactivated.

23. Tell me about your understanding of SSR?

  • SSR is server-side rendering, that is, the work of Vue rendering tags into HTML on the client side is completed on the server side, and then the html is directly returned to the client side.

  • Advantages of SSR

    • Better SEO
    • First screen loading speed is faster
  • Disadvantages of SSR

    • Development conditions will be restricted, server-side rendering only supports two hooks beforeCreate and created
    • When we need some external extension libraries, special processing is required, and the server-side rendering application also needs to be in the Node.js runtime environment
    • More server load

24. What Vue performance optimizations have you done?

  • Coding stage

    • Try to reduce the data in the data, the data in the data will increase the getter and setter, and the corresponding watcher will be collected
    • v-if and v-for cannot be used together
    • If you need to use v-for to bind events to each element, use event proxy
    • SPA page uses keep-alive cache component
    • In more cases, use v-if instead of v-show
    • The key is guaranteed to be unique
    • Use routing lazy loading, asynchronous components
    • Anti-shake, throttling
    • Import of third-party modules on demand
    • Dynamic loading of long list scrolling to visible area
    • Image lazy loading
  • SEO optimization

    • Pre-render
    • Server-side rendering SSR
  • Packaging optimization

    • Compressed code
    • Tree Shaking/Scope Hoisting
    • Use cdn to load third-party modules
    • Multi-threaded packaging happypack
    • splitChunks extract public files
    • `sourceMap optimization
  • user experience

    • Skeleton screen
    • You can also use cache (client-side cache, server-side cache) optimization, server-side open gzip compression, etc.