preface

As 2019 draws to a close, is it time to fight again for a better 2020? ‘It is a man who is ashamed to bear his shame. Jiangdong children more talented, comeback unknown ‘, those who failed in the autumn recruit, is willing to give up?!

This article summarizes my experience since 2019 and browse the articles, some popular interview questions, covering from CSS to JS to Vue to network and other front-end basic to advanced knowledge.

Summarizing the knowledge points involved in the interview questions is a promotion for myself, and I hope it can help students to have a better competitive ability in 2020.

  • CSS article – Juejin. Im/post / 684490…
  • Javavscript article – Juejin. Im/post / 684490…
  • ECMAScript six papers – Juejin. Im/post / 684490…

Module Four – Vue

“About Base”

What is your understanding of MVVM? How is it different from MVC?

  • MVCRefers to theModel-View-Controller, namely, model-view-controller.
    • useMVCIs to separate the model from the view
    • MVCBelongs to one-way communication, must passControllerThe controller must retrieve the data, return the results to the front end, and re-render the page
  • MVVMRefers to theModel-View-ViewModelModel-view-viewmodel, where “model” refers to the data passed in the back end, “view” refers to the page that is seen, and “viewmodel” isMVVMAt the heart of it is connectivityViewwithModelThe bridge,implementationviewIs automatically updated toviewModel,viewModelChanges in will also automatically appear inviewon, it is a kind ofData-driven viewThe model

The difference between:

  • MVCIn theControlinMVVMTranslated intoviewModel
  • MVVMThe view is displayed through data, not through node operations
  • MVVMBasically solved the problemMVCIn a large number ofDOMThe page rendering performance is reduced, the loading speed is slow, and the user experience is affected

Please explain the principle of Vue responsive data?

The core of Vue for responsive data is object. DefineProperty. When Vue initializes data, it will use Object. Dependencies are collected through the Dep class (the watcher for the current component is collected), and if the property changes, the dependent is notified to call its update method for an update operation

  • Conclusion:VueThrough data hijacking with a publisher-subscriber design pattern, internally through invocationobject.defineProperty()To hijack the propertiesgetterandsetter, notifying subscribers of changes in data and triggering the appropriate callback

About the underlying source code, can take a look at this article: segmentfault.com/a/119000001…


How does Vue implement responsive data?

Vue bidirectional data binding: Data changes update view, view changes update data, for example, when the input content changes in the input box, data in data changes synchronously. When data in data changes, the content of the text node changes synchronously

Vue implements responsive data through the following four steps

  • Implement a listener “Observer” : to iterate over the data object, including the properties of the child property object, usingObject.defineProperty()I’m going to add to the propertiesgetterandsetterIf you assign a value to an object, it will triggersetter, so you can listen for data changes
  • Implement a parser “Compile” : parseVueTemplate directive, replace variables in the template with data, and then initialize the render page view, bind the corresponding node of each directive to update function, add subscribers to listen for data, once the data changes, receive notification, call update function to update data
  • Implement a subscriber “Watcher” :WatcherThe subscriber isObserverandCompileBetween the communication bridge, the main task is subscriptionObserverThe parser is triggered when a message about a property value change is receivedCompileThe corresponding update function in
  • Implement a subscriber “Dep” : The subscriber uses a publish-subscribe design pattern to collect subscribersWatcher, to the listenerObserverAnd the subscriberWatcherUnified management

How does Vue implement listening on objects and arrays?

Since object.defineProperty () can only data hijack attributes, not entire objects (arrays), the Vue framework hijack each attribute by going through sets and objects. Object.defineproperty () can also be used to listen on objects and arrays (partial method operations)


Can Vue detect changes in an array item assigned directly?

Due to JavaScript limitations, Vue cannot detect the following array changes

  • When usingThe indexWhen setting an array entry directly, for examplevm.items[indexOfItem] = newValue
  • When you modify the arrayThe length of theWhen, for example,vm.items.length = newLength

To solve the first problem, Vue provides the following operations

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)

// vm.$set, vue.set an alias vm.$set(vm.items, indexOfItem, newValue)

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

To solve the second problem, Vue provides the following operations

// Array.prototype.splice
vm.items.splice(newLength - 1)
Copy the code

How does Vue detect changes in an array?

  • Core idea: Use function hijacking to override array methods (Push and pop, unshift, shift...)
  • VuewilldataThe array in which the prototype chain is rewritten points to the array prototype method defined by itself when calling the array’sAPIIf the array contains a reference type, the reference type in the array is monitored again

How does Vue passvm.$set()To solve the problem of objects not responding to new/deleted attributes?

Due to JavaScript limitations, Vue cannot detect the addition or removal of object attributes. This is because Vue hijacks the getters and setters of the properties when initializing the instance, so the properties must exist on the data object for Vue to transform them into responsive data.

Vue provides Vue. Set (object, propertyName, value)/vm.$set(object, propertyName, value) to add responsive properties to an object.

  • If the target is an array, use the array directlyspliceMethod to trigger a response
  • If the target is an object, it first determines whether the object property exists, whether the object is responsive, and finally, if the property is to be responsive, it is calleddefineReactive()Method for response processing (defineReactive()Is the VueObject.defineProperty()Secondary encapsulation)

Why did Vue take asynchronous rendering?

Because if asynchronous rendering is not adopted, the data will be re-rendered every time. In order to improve performance, Vue uses asynchronous rendering to update the view asynchronously after this round of data update


What are the disadvantages of “translating” object.defineProperty? (Why did Vue3.0 start using Proxy to implement responsiveness)

  • Object.definePropertyYou can only hijack the properties of an object, so you need to traverse every property of the object, whileProxyObjects can be directly represented
  • Object.definePropertyThe new attributes need to be observed manually becauseObject.definePropertyIt is the properties of the object (point 1) that are hijacked, so when a new property is added, the object needs to be traversed again to use the new propertyObject.definePropertyThis is the reason why we are givingdataTo add properties to an array or object in$setSo that the view can be updated)
  • ProxyHigh performance. Supports 13 interception modes

What are the pros and cons of the virtual Dom?

Advantages:

  • Guaranteed performance limits: virtualisation of the frameworkDomNeed to adapt some of its operations to any upper-level API that may be generatedDomThe implementation of the operation must be universal, so its performance is not optimal, but it is more violentDomThe operation is much better, thus ensuring a lower limit on performance
  • No manual operationDom: The framework will be based on the virtualDomTwo-way binding with data to help us update views and improve development efficiency
  • Cross-platform: VirtualDomEssentially,JavaScriptObject, but realDomAnd platform related, compared to virtualDomIt can work better across platforms

Disadvantages:

  • Extreme optimization is not possible

How does the virtual Dom work?

The implementation principles of virtual Dom mainly include the following three parts:

  • withJavaScriptObject simulation realityDomTree, to the realDomabstract
  • throughdiffAlgorithm for two virtualDomObject to compare
  • throughpatchThe algorithm will make two virtualDomObject differences apply to realityDomThe tree

How does nextTick work? What’s the role in Vue

  • Principle:EventLoopEvent loop
    • The correct process is to detect the existence of the Promise. Then → the callback function of the MutationObserver → setImmediate → setTimeout, and use it to determine which API the callback queue is executed asynchronously
    • Received one in the nextTick functioncallbackInstead of calling it, push it to a global queue and wait for the next queue to execute all the functions in the queue at once
    • This queue may be a microTask queue and the page may be a macroTask queue. The first two apis belong to the microTask queue and the last two belong to the macroTask queue
  • Role: next timedomA delayed callback is performed at the end of the update loop and is used immediately after we modify the datanextTick()To get the latest update of the Dom

How is deep:true in Watch implemented?

When the user specifies deep:true in Watch, if the value currently monitored is an array type (object type), each item in the object will be evaluated, and the current watcher will be stored in the dependency of the corresponding property. In this way, the data will be notified to update if the object in the array changes

This is essentially because Vue will recursively access a watch with deep set (as long as the property is also responsive), and the dependency collection process will continue

Disadvantages: Because you need to operate each item, the performance will be degraded. Therefore, you are not advised to use deep:true multiple times


Why is v-if and V-for not recommended together?

V-for has a higher priority than V-if. If used together, v-IF will be added to every element, and it will be a waste of performance to run repeatedly in every V-for loop


Why should the data of the “translate” component be written as a function

In Vue, components are reusable. After a component is created, it can be reused in multiple places. No matter how many times it is reused, the data in the component must be isolated from each other and do not affect each other. When you declare a component multiple times in a template, the data in the component will point to the same reference, and changing the data in one component will change the data in other components. So data must be returned as a function

  • Summary: In order to achieve this, each component instance can maintain a separate copy of the data and not interact with each other

❗ tidbit: The new Vue root component does not need to be reused and therefore does not need to be returned as a function


What is the function of key in V-for?

Key is to specify a unique ID for each Vnode. In the Diff process of vnodes at the same level, we can quickly compare the key to determine whether it is the same node, and use the uniqueness of key to generate a map to obtain the corresponding node faster. In addition, the accuracy of rendering can be guaranteed after the key is specified.

Im /post/684490


When is Vue invoked per lifecycle?

  • beforeCreate→ After instance initialization, data observation (data observer) was called before
  • created→ The instance is called after it has been created. Here, the instance has completed the following configuration:
    • Data observation (data observer)
    • Operations on properties and methods
    • watch/eventEvent callback
    • But not here$el
  • beforeMount→ Called before the mount begins, relevantrenderFunction is called for the first time
  • mounted$elNewly createdvm.$elReplace, and then mount it to the instance
  • beforeUpdate→ Data update when called, occurs in virtualDOMRe-render and patch before
  • updated→ Virtual due to data changesDOMRe-render and patch, after which the hook is called (it is not called during server-side rendering)
  • beforeDestroy→ Called before instance destruction, where the instance is still fully usable
  • destroyedVueCalled after instance destruction. When this hook is called,VueEverything indicated by the instance is unbound, all event listeners are removed, and all child instances are destroyed (this hook is not called during server-side rendering).


What can Vue do within each lifecycle?

  • created→ The instance has been created, because it is the earliest triggered, so can carry on some data, resource request
  • mounted→ The instance has been mounted, you can do someDOMoperation
  • beforeUpdate→ You can further change the state in this hook without triggering additional rendering
  • updated→ Can be executed depending onDOMIn the operation. In most cases, however, you should avoid changing the state in this hook, as this can result in an infinite loop of updates
  • destroyed→ You can perform some optimization operations, such as clearing the timer, clearing the cache, unbinding the event, etc

What declaration lifecycle hooks do Vue components have?

BeforeCreate, Created, beforeMount, Mounted, beforeUpdate, Updated, beforeDestroy, Destroyed

❗ Tips:

< keep alive – > have their own independent of hook function activated | deactivated

  • activatedAnd in the<keep-alive>Use this hook when the component is activated
  • deactivatedAnd in the<keep-alive>Use this hook when the component is stopped

What is the order in which Vue’s parent and child lifecycle hooks are executed?

  • Understand the rendering process:

The parent component is mounted only after the child component is mounted. Therefore, the parent component must be mounted after the child component is mounted

So: Parent beforeCreate → Parent created → Parent beforeMount → Child beforeCreate → Child created → child beforeMount → Child Mounted → Parent mounted

  • Child component update process (depending on whether the parent component is affected)

    • The parent component is affected: “parent” beforeUpdate → “child” beforeUpdate → “child” updated → “parent” updated
    • Does not affect the parent component: “child” beforeUpdate → “child” updated
  • Parent component update process (depending on whether it affects child components)

    • Child components are affected: “parent” beforeUpdate → “child” beforeUpdate → “child” updated → “parent” updated
    • Does not affect the child components: “parent” beforeUpdate → “parent” updated
  • Destruction of the process

    • “Parent” beforeDestroy → “child” beforeDestroy → “child” Destroyed → “parent” destroyed

Can a parent component listen to the lifecycle of a child component?

If the Parent component (Parent) and the Child component (Child) are mounted, the Parent component (Parent) hears that the mounted component is mounted, and the Parent component (Child) hears that the mounted component is mounted.

  • Methods a
// Parent.vue
<Child @mounted='doSomething' />

// Child.vue
mounted(){
    this.$emit('mounted')}Copy the code
  • Method 2 (easier – listening via @hook)
// Parent.vue
<Child @hook:mounted='doSomething' />

# @hook can listen to other life cycles
Copy the code

How to understand vUE unidirectional data flow

  • invueIn, the parent component can passpropPass the data to the child component, but thispropIt can only be modified by the parent component. If the child component is modified, it will throw an error
  • If a child component wants to modify the data, it must pass$emitThe child component dispatches the event, and the parent component receives the event for modification

Why can’t a child modify a Prop passed by its parent? (Why vUE advocates one-way data flow)

Because Vue advocates one-way data flow, updates to the parent props flow to the child components, but not vice versa. This is to prevent accidental changes to the state of the parent component, making the flow of the application data difficult to understand. The cost of debugging can be very high when the application is complex if a single data stream is corrupted


What are the communication methods between components?

  • Parent-child communication

    • props / event
    • $parent / $children
    • ref
    • provide / inject
    • .sync
  • Non-parent component communication

    • eventBus
    • By the root instance$root
    • vuex
    • $attr / $listeners
    • provide / inject

❗ Tips: About using.sync

Suppose you have a component comp <comp :foo.sync="bar"></comp> Pass foo and sync, which is extended to <comp :foo="bar" @update:foo="val => bar = val"></comp>
Copy the code
When the child comp needs to update the value of foo, it needs to explicitly fire an update event called this.$emit('update:foo', newValue)
Copy the code

Talk about the dynamic components of vUE

When multiple components switch through the same mount point, the is value is the name of the component, then the page will display the component

<div :is='xxx'></div>
Copy the code

Let’s talk about the use of recursive components

Components can call themselves in their own templates, but they can only do this with the name option

(Max stack size exceeded) (Max stack size exceeded) (Max stack size exceeded) (Max stack size exceeded) (Max stack size exceeded) (Max stack size exceeded) (Max stack size exceeded) (Max stack size exceeded) Therefore, we should use v-if = ‘false’ as the end condition for the recursive component. When v-if = ‘false’ is encountered, the component will no longer render

How is the custom component syntax sugar V-Model implemented? (How to implement bidirectional binding with V-Model)

V-model is essentially the syntactic sugar of V-bind and V-ON to create bidirectional bindings on form controls or components (just syntactic sugar to distinguish reactive data). Principle: Bind vlUE to form elements and listen for input events

<input v-model='searchText'<input v-bind:value='searchText'
    v-on:input='searchText = $event.target.value'>
Copy the code

Using v-Model on a component binds the component to a prop named Value and an event named Input by default


What’s the difference between a Vuex and a pure global object?

There are two main differences between vuex and global objects:

  • vuexThe state store of is reactive. whenvueComponents fromstore, ifstoreChanges in the state of, and the corresponding components are efficiently updated
  • You can’t change it directlystoreChange the state ofstoreThe only way to state in is to submit it explicitlymutation(commit). This makes it easy to track each state change

Why cannot asynchronous operations be performed on VUex mutation?

The only way for all status updates in VUEX is to commit mutation, and asynchronous operations need to commit mutation (Dispatch) via action. This allows us to easily track each state change, which allows us to implement tools to help us use VUex better

Each mutation is executed with a new state change, so devTools can take a snapshot and save it, and then implement time-travel.

If the mutation supports asynchronous operations, there is no way to know when the state was updated, and state tracking cannot be done well, affecting debugging efficiency


What’s the difference between v-show and V-if?

  • v-ifThe node where the current instruction resides will not be rendered if the condition is not trueDomElement, the event listener and child components of the conditional block are destroyed and rebuilt during the switch
  • v-showOnly based oncssToggle and render regardless of the condition (toggledisplay:block | none)

So: V-IF switching costs a lot, while V-show initialization costs a lot. Therefore, v-show is more appropriate when the Dom elements that are displayed and hidden need to be switched frequently. V-if is more appropriate when the Dom elements that are rarely switched after rendering


What is the difference between computed and watch?

  • computedIs a calculated value that depends on other properties and is cached and updated only when the value of the dependency changes (automatically listens for changes in the value of the dependency and dynamically returns the content)
  • watchWhen the property you are listening for changes, you trigger a callback and execute some logic in the callback

Actually computed has its own watcher, which has a dirty attribute to determine whether the value of computed needs to be recalcomputed or directly reused, such as in this example:

computed: {
    sum() {
        return this.count + 1
    }
}
Copy the code
  1. insumReactive properties are read the first time you evaluate themcountTo collect this responsive data as a dependency. And compute a value to store in its ownvalueOn,dirtySet it to false and then access it in the templatesumI just return this valuevalueIs not re-evaluated.
  2. If the count changes, the watcher is told to set the dirty attribute to true, which turns the re-evaluation switch on. And that makes sense, because only if count changes does sum have to be evaluated again.
  3. The next time the template calls this.sum, it will actually call the sum function again, set the dirty to false again, and wait until it is enabled again

So: Computed and watch differ in usage. Computed is suitable for template rendering. If you need to obtain dynamic values through dependencies, you can use computed properties. If you want to execute business logic while listening for changes in values, use Watch


What does V-HTML do in Vue? What problems can it cause?

V-html can be used to identify HTML tags and render them

The problem: Rendering arbitrary Html dynamically on a web site makes it vulnerable to Xss attacks, so v-HTML can only be used on trusted content, and never on user-submitted content


What is the role of keep-alive in Vue?

Components wrapped in

save the state of their components when toggled, preventing them from being destroyed and preventing multiple renderings

  • It is commonly used in combination with routing and dynamic components to cache components
  • keep-aliveHas two separate life cycles (activated | deactivated),keep-aliveThe components of the package are not destroyed when switched, but are cached in memory and executeddeactivatedHook, gets memory when switching back to component, executes after renderingactivatedhook
  • provideincludeandexcludeProperty, both support strings or regular expressions
    • includeIndicates that only components with matching names will be cached
    • excludeIndicates that any component with a matching name will not be cached
    • excludePriority overinclude

How do I add a custom directive?

  • Create local instruction
var app = new Vue({
    el: '#app', data: {}, // Creates directives: {// Directives name dir1: {el) {// toDo}}}})Copy the code
  • Create global directive
Vue.directive('dir2', {inserted(el) {// inserted means element inserted // toDo}})Copy the code
  • Instructions to use
<div id="app">
    <div :dir1='.. '></div>
</div>
Copy the code

How do I customize filters

  • Creating local filters
var app = new Vue({
    el: '#app', data: {}, // create directive (can be multiple) filters: {// directive name newfilter:function(value){
            // toDo
        }
    }
})
Copy the code
  • Creating a Global Filter
Vue.filter('newfilter'.function (value) {
    // toDo
})
Copy the code
  • Filter use
<div>{{xxx | newfilter}}</div>
Copy the code

What are the commonly used modifiers for Vue?

  • .prevent: Intercepts default events
  • .passive: Do not intercept default events
  • .stop: Prevents event bubbling
  • .self: Fired when an event occurs on this element instead of a child element
  • .captureEvent listener, which is called when an event occurs

How to dynamically bind Class/Style

Classes can be dynamically bound through object and array syntax

  • Object syntax
<div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>

data: {
  isActive: true,
  hasError: false
}
Copy the code
  • Array syntax
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}
Copy the code

Styles can also be dynamically bound through object and array syntax

  • Object syntax
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

data: {
  activeColor: 'red',
  fontSize: 30
}
Copy the code
  • Array syntax
<div v-bind:style="[styleColor, styleSize]"></div>

data: {
  styleColor: {
     color: 'red'
   },
  styleSize:{
     fontSize:'23px'}}Copy the code

Describe the understanding of SPA single page, and what are its advantages and disadvantages?

SPA(SingLG-Page Application) only loads the corresponding Html, JavaScript and Css when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page because of the user’s operation. Instead, a routing mechanism is used to transform Html content, UI interaction with the user, and avoid page reloading

  • Advantages:
    • Good user experience, fast loading, content changes do not need to reload the entire page, avoid unnecessary jump and repeat rendering
    • SPA has relatively little pressure on the server
    • The responsibilities of the front and back end are separated, and the architecture is clearer. The front end carries out interactive logic, and the back end is responsible for data processing
  • Disadvantages:
    • The first loading is time-consuming (to achieve the function and display effect of a single-page Web application, you need to load the pageJavaScript.CssUnified loading, some pages on demand loading)
    • Since single-page applications display everything on a single page, you can’t use the browser’s forward and backward functions, and all page transitions need to be managed on your own stack
    • Not conducive to SEO optimization

How do I make CSS work only in the current component

Just write scoped to the


“About the Router”

What is the difference between a route and a router?

  • routeRepresents a route information object, includingpath.params.hash.query.fullPath.matched.nameRouting information parameters
  • routerRepresents the route instance object, including route jump method, hook function and so on

“Translate” the navigation guards in the VUe-router

  • Global front hook:beforeEach.beforeResolve.afterEach
  • Route Exclusive Guard:beforeEnter
  • Component Internal Guard:beforeRouteEnter.beforeRouteUpdate.beforeRouteLeave

Navigation parsing process:

  • Navigation triggered
  • Called in an inactive componentbeforeRouteLeaveLeave the guards
  • Call globalbeforeEachThe guards
  • Called in a reused componentbeforeRouteUpdateThe guards
  • Called in the routing configurationbeforeEnterThe guards
  • Resolve the asynchronous routing component
  • Called in an activated componentbeforeRouteEnterThe guards
  • Call globalbeforeResolveThe guards
  • Navigation confirmed
  • Call globalafterEachThe guards
  • The triggerDomupdate
  • Called with the created instancebeforeRouteEnterGuard passnextThe callback

What is the difference between the hash/History modes on the VUe-Router?

  • hashModel will beurlDisplays ‘#’ on thehistoryModel does not
  • When you refresh the page,hashThe mode can be loaded normally tohashValue corresponds to the page,historyIf the pattern is not processed, it returns 404, which generally requires the back end to configure all pages to redirect to the home page
  • For compatibility,hashMode can support earlier versions of browsers and IE

How is hash/history implemented in vue-Router?

  • hashmodel
    • #behindhashValue change, will not cause the browser to the server to send a request, the browser does not send a request, will not refresh the page, while listeninghashchangeEvents can be knownhashWhat has changed. According to thehashChanges to implement partial updates to the page
  • historymodel
    • historyThe implementation of the pattern, mainlyHtml5The two apis published by the standard (pushStateandreplaceState), these two apis can be changedurl, but will not send the request, so you can listenurlTo implement local updates

How to define dynamic routes for vue-router? How do I get the value passed in

  • Dynamic routing is created by usingpathProperty, using the dynamic path parameter, starting with a colon
{
    path:'/details/:id',
    name:'Details',
    components:Details
}

Access paths under the 'details' prefix, such as' details/1', 'details/2', etc. will map to the 'details' component
Copy the code
  • When the match to/details, the parameter value is set tothis.$route.paramsSo you can get dynamic parameters from this property
this.$route.params.id
Copy the code

What are the parameter transmission modes of vue-router?

  • throughparams
    • Can only usenameAnd don’t usepath
    • The parameter will not be displayed inurlon
    • Browser force refresh will clear the parameters
  • throughquery
    • Can only usepathAnd don’t usename
    • nameYou can usepathThe path
    • The parameters will be displayed inurlon
    • The parameters are not cleared when the browser is refreshed

“About Vuex”

What are the pros and cons of VUEX?

  • advantages
    • Addresses messaging for non-parent components (storing data instateC)
    • To reduce theAjaxRequest times, some scenarios can be directly from memoryStateTo obtain
  • disadvantages
    • Refresh the browser,vuexIn theStateIt will go back to the initialized state

What are the properties of VUex?

  • StatevuexBasic data used to store variables
  • Getter: From basic datastateDerived data, equivalent tostateCalculated properties of
  • Mutation: The method for submitting updated data, which must be synchronous (used if asynchronous is required)action). eachmutationBoth have a string event type (type) and a callback function (handler)
  • ActionAnd:mutationIs basically the same, but the difference is
    • actionIs submittedmutationInstead of changing the state directly
    • actionAny asynchronous operation can be included
  • Module: modularvuex, each module can have its ownstate.mutation.action.getter, make the structure clear, convenient management

What are the features of state in VUex?

  • vuexIt’s a repository, and the repository is filled with a lot of objectsstateThat’s where the data source is
  • stateThe data stored in it is responsive,VueComponents fromstore, if yesstoreThe components that depend on the data are also updated
  • It does this bymapStateThe globalstateandgettersMapped to the current componentcomputedCompute attributes

What are the features of getters in Vuex?

  • gettersCan bestateTo do the computation, you can view it asstorethecomputedCalculate attribute
  • It is possible to compute properties in components, butgettersIt can be reused across multiple components
  • If a state is only used within a component, it is not requiredgetters

Should the code for Ajax requests in Vue be written in the component’s Methods or vuex’s Actions?

  • If the requested data is not common to other components and is used only within the requested component, it does not need to be put invuexthestateIn the
  • If reused elsewhere, the request can be placed inactionIn, easy to reuse; If you do not need to reuse this request, write it inVueIt’ll be more convenient in the file

“About SSR”

Have you ever used SSR? Let’s talk about the understanding of SSR

Vue.js is a framework for building client applications. By default, Vue components can be exported to the browser to generate and manipulate the Dom. However, you can also render the same component as Html strings on the server, send them directly to the browser, and finally activate those static tags as fully interactive applications on the client

This process is called SSR (server rendering). This process is called SSR (Server rendering). This process is called SSR (Server rendering).

Advantages of server-side rendering SSR:

  • Better SEO: due toSPAThe content of the page is throughAjaxWhile search engine crawl tools do not waitAjaxAsynchrony is completed before grabbing the page content, so inSPAThe page is not crawled throughAjaxThe content obtained; whileSSRThe rendered page is returned directly by the server (the data is already contained in the page), so the search engine crawl tool can crawl the rendered page
  • Faster content arrives at the event (first screen loads faster) :SPAWill wait for allVueThe compiledJsAfter all files are downloaded, page rendering is started. It takes some time to download files, so it takes some time to render the first screen. whileSSRDirectly rendered by the server page directly back to display, without waiting for downloadJsFile before rendering, soSSRThere are faster content arrival times

Disadvantages of server-side rendering SSR:

  • More development conditions: for example, server-side rendering is only supportedbeforeCreate.createdLifecycle hooks, which result in some external extension libraries requiring special handling to run in a server-side rendering application; And with a fully static single-page application that can be deployed on any static file serverSPAThe server rendering application needs to be inNodeJsOperating in the environment
  • More server load: inNodeJsThe rendering of a complete application would obviously be better than just providing static filesserverConsumes more CPU resources