The understanding of the MVVM

  • MVVM, which stands for Model-view-ViewModel, is a software architecture style,
  • The core is data-driven, the ViewModel, which is a relational mapping of View and Model.
  • The essence of MVVM is to operate the View and then operate DOM based on the operation data. With the help of MVVM, there is no need to operate DOM directly. Developers only need to write business in the ViewModel, making the View fully automated.

Spa applications and advantages and disadvantages

Spa is a single page application, that is, a Web project has only one HTML file, and content switching is implemented through routing

advantages

  • Page switching provides a better user experience without the need to reload the entire page
  • The service items have relatively low pressure
  • The responsibilities of the front and back end are separated and the structure is clear

disadvantages

  • The home page takes a long time to load. Static resources such as JS and CSS must be loaded in a unified manner
  • Browser forward and backward navigation fails, and since there is only one page, you need to build your own stack management
  • Seo optimization is difficult because everything is displayed on one page

The life cycle

The process from creation to illumination of a Vue instance is the life cycle

! Note: The browser has 8 hooks, but node only has beforeCreate and Created for server-side rendering

  • beforeCreateisnew Vue()Then the first hook is triggered in the current phaseData, methods, computedAs well aswatchThe data and methods on the.
  • createdIt happens after the instance has been created, the current phase has completed the data observation, that is, the data can be used, the data can be changed, and the data can’t be changed hereupdatedFunction. You can do some initial data fetching, you can’t interact with the Dom at this stage, you can pass if you want tovm.$nextTickTo access the Dom.
  • beforeMountOccurs before mounting, after the template template has been imported into the rendering function for compilation. At this stage, the virtual Dom has been created and is about to start rendering. Changes can also be made to the data at this point without triggeringupdated.
  • mountedOccurs after the mount is complete. In the current stage, the actual Dom is mounted, the data is bidirectional bound, and the Dom node can be accessed using$refsProperty to manipulate the Dom.
  • beforeUpdateIs triggered before the update, when the responsive data is updated and the virtual DOM is re-rendered, and you can make changes to the data at this stage without re-rendering.
  • updatedOccurs after the update is complete, and the component Dom of the current phase has been updated. It is important to avoid changing the data during this period, as this may result in an infinite loop of updates.
  • beforeDestroyThis occurs before the instance is destroyed, and the instance is fully usable in the current phase, where we can clean up the loose ends, such as clearing timers and destroying repeated listening by the parent to the child.beforeDestroy(){Bus.$off("saveTheme")}
  • destroyedOccurs after instance destruction, at which point all that is left is the DOM shell. Components have been disassembled, data bindings removed, listeners removed, and subinstances destroyed

Lifecycle call order

  • Components are called in parentafter child order
  • The order of rendering completion is child before parent
  • The destruction of a component is parent after child
  • Destruction is completed in the order of children first and then parents

Load render 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

Process parent beforeDestroy-> Child beforeDestroy-> Child destroyed-> Parent destroyed

What is the role of the VUE lifecycle

It has multiple event hooks throughout its lifecycle, making it much clearer how we control the Vue instance.

Which hooks are triggered the first time the page loads

BeforeCreate, Created, beforeMount, and Mounted are triggered the first time a page is loaded

Which scenarios are appropriate for each cycle

  • Beforecreate: You can add a loading event here, which is triggered when the instance is loaded
  • Created: This is where the initialization event is written. For example, this is where the loading event ends and asynchronous requests are called
  • Mounted: A DOM node is obtained after an element is mounted
  • BeforeDestroy: Clears timer nextTick: manipulates DOM immediately after updating data

Difference between V-if and V-show

v-if

  • True conditional rendering, the V-IF toggle destroys the reconstructed component and dom
  • Is lazy, if the initial condition is false, it will not render until the first condition is true

v-show

  • Renders regardless of whether the initial conditions are true or false, and shows and hides by controlling the display property

Summary: V-show applies to scenarios with frequent switching conditions, and V-IF applies to scenarios with few switching conditions

Vue one-way data flow

The props can only flow from the parent component to the child component and vice versa. This prevents the props from accidentally changing the state of the parent component from the child component, thus causing a chaos in the data flow of your application. To change the parent component data, you must manually trigger a parent component event via $emit. Subcomponents use props when the parent component changes its own data

  • Direct use ofpropsIn data, define a variable to receive props
props:['index'].data(){
return {
 subIndex: this.index
}
}
Copy the code
  • The need topropsWhen transforming, define a calculated property
props:['index'].computed: {subIndex(){
  return this.index +1}}Copy the code

Which lifecycle the asynchronous request is placed in

Mounted creates an asynchronous request. Created creates an asynchronous request.

  • createdthanmountedEarly execution, can get asynchronous data rendering faster, reduce load time
  • SSR does not support beforeMount and Mounted hook functions, so creating helps consistency

What are the communication modes of Vue2. X components

Father and son components

  • Parent –> child: props –> parent: $emit
  • Get the parent component instance:$parent / $children: this.$parent. Show ()//show is defined in the parent component
  • throughrefGets the child component instance (if used on a normal DOM element, the reference refers to the DOM element; If used on a child component, the reference refers to the component instance.For example, mount a: ref="comA" on the label of the imported subcomponent, and then use the data in the method or subcomponent, this. coderefs.com a.tabs
  • Dojo.provide, injectIt is not officially recommended, but is commonly used when writing component libraries

Brother components

  • Prototype.$Bus = new Vue
  • Vuex

Across the component level

  • Vuex
  • attrs,listeners
$attrs: contains property bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop. When a component does not declare any prop, all parent-scoped bindings (except class and style) are included, and the internal component can be passed in via v-bind="$attrs". Often used in conjunction with the inheritAttrs option. $listeners contain V-on event listeners in the parent scope (without.native modifiers). It can be passed into internal components via V-on ="$Listeners"Copy the code
  • Dojo.provide, inject
/ / the parent component
<template>
    <div id="app">
    </div>
</template>
    <script>
        export default {
            data () {
                    return {
                        datas: [{id: 1.label: 'Product 1'
                            }
                        ]
                    }
            },
            provide {
                return {
                    datas: this.datas
                }
            }
        }
    </script>
    
    / / child component
<template>
    <div>
        <ul>
        <li v-for="(item, index) in datas" :key="index">
            {{ item.label }}
        </li>
        </ul>
    </div>
</template>
    <script>
        export default {
            inject: ['datas']}</script>
Copy the code

What is the SSR

SSR is server side rendering, which means Vue renders the tags into HTML on the server side, and then returns the HTML directly to the client side.

Advantages and disadvantages of server rendering SSR are as follows:

(1) Advantages of server-side rendering:

  • Better SEO: Because the content of SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the completion of Ajax asynchronism before grabbing the page content, so the content of SPA page obtained through Ajax cannot be captured; SSR is directly returned by the server to the rendered page (data has been included in the page), so the search engine crawler can grab the rendered page;
  • Faster content arrival time (faster loading on the first screen) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. File download takes a certain amount of time, so rendering on the first screen takes a certain amount of time. SSR directly returns the page rendered by the server directly, without waiting to download JS files and render again, so SSR has a faster content arrival time;

(2) Disadvantages of server-side rendering:

  • More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, resulting in some external extension libraries requiring special handling to run in server-side rendering applications; And unlike fully static single-page application SPA, which can be deployed on any static file server, server-side rendering applications need to be in the Node.js server running environment;
  • More server load: Rendering a full application in Node.js is obviously more CPU-intensive than a server that only serves static files, so if you expect to use it in a high traffic environment, Prepare your server load and use caching strategies wisely.

Vue routing

The two routing modes are described as follows:

  • Hash: Uses the URL hash value for routing. Support for all browsers, including those that don’t support the HTML5 History Api;
  • History: Relies on the HTML5 History API and server configuration;

Principle of Hash Mode

The implementation of the hash route is based on location.hash, where the value of location.hash is the content after the # in the URL.

  • When a request is made to the server, the hash value (after the # sign) is not sent
  • You can use the A labelhrefProperties, orlocation.hashChanging the hash value redirects the page without refreshing the page
  • You can usehashchangeThe event listens for changes in the hash value and changes the content display
  • Changing the hash value adds a new entry to the browser’s history, so you can use forward and backward navigation

Principle of History Mode

History.pushstate () and history.replacestate () are two apis, one for adding and one for replacing a history

  • Both apis allow you to manipulate browser history without refreshing the page
  • Can be achieved bypopStateEvent that listens for URL changes and renders a new page
  • history.pushStateandhistory.replaceStateThe popState event is not triggered

Vue project performance optimization

The code level

  • V-if and V-for are used in different scenarios
  • Computed and Watch are used in different scenarios
  • V-for traversal, add key to each item
  • Route lazy loading
  • Lazy loading of image resources
  • Events to destroy
  • Third-party plug-ins are introduced on demand

Webpack level

  • Use loader to compress code and static resources
  • Treeshaking is reduced for code
  • Optimize sourceMap
  • Extracting CSS files
  • Project compilation optimization

Web basic technology optimization

  • CDN caches static resources
  • Use browser caching wisely
  • Use Chrome Performance to find Performance bottlenecks

The role of keys in Vue

The key is a unique token for a Vnode in a Vue. With this key, our diff operation can be more accurate and faster

V – the principle of the model

V-model is mainly used on input, Textarea, SELECT and other form elements to achieve two-way binding. In fact, it is just a syntax sugar, binding different attributes for different form elements internally, and throwing different events

<input v-model='something'>
Copy the code

The equivalent of

<input v-bind:value="something" v-on:input="something = $event.target.value">
Copy the code

Why is Data in a Vue component a function

When a component is reused multiple times, multiple instances are created. Essentially, these instances all use the same constructor. If data is an object, the object is a reference type that affects all instances. So to ensure that data does not conflict between different instances of the component, data must be a function. The instance of new Vue is not reused, so there is no object reference problem.

Understanding keep-alive

Keep-alive is a built-in component of vue. Wrapped components retain their state to avoid repeated rendering

  • provideincludeexcludeAttribute, both of which support strings or regular expressions. Include indicates that only components with matching names are cached, and exclude indicates that components with matching names are not cached. Exclude has a higher priority than include.
  • There are two hook functionsactivateddeactivatedWhen the component is activated, the hook function is triggeredactivatedTriggers the hook function when a component is removeddeactivated.

Method by which a parent component listens for the life cycle of a child component

Using the $emit

// Parent.vue
<Child @mounted="doSomething"/>
// Child.vue
mounted() {
  this.$emit("mounted");
}
Copy the code

Use @ hock to monitor


// Parent.vue
<Child @hook:mounted="doSomething" ></Child>
doSomething() {
   console.log('Parent listens to mounted hook function... ');
},
// Child.vue
mounted(){
   console.log('Child component triggers mounted hook function... ');
},     
// The output sequence is as follows:
// The child triggers the mounted hook function...
// The parent listens to the mounted hook function...
Copy the code

The computed and watch

computed:

Computed is a computed property,computed value, and it’s used more in scenarios where values are computed computed is cacheable,computed values are cached after the getter is executed, and only after the value of the property that it depends on changes, The next time the value of computed is obtained, the corresponding getter is invoked to compute computed

watch:

This is more of a “watch” function, similar to the listening callback for some data, which is used to observe the props $emit or the value of this component. When the data changes, the callback is performed for subsequent operations without caching, and the page is re-rendered without changing the value

Summary:

When we’re doing numerical calculations, and we’re relying on other data, let’s design this for computed and if you need to do something when the data changes, use watch to see what the data changes