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?
MVC
Refers to theModel-View-Controller
, namely, model-view-controller.- use
MVC
Is to separate the model from the view MVC
Belongs to one-way communication, must passController
The controller must retrieve the data, return the results to the front end, and re-render the page
- use
MVVM
Refers to theModel-View-ViewModel
Model-view-viewmodel, where “model” refers to the data passed in the back end, “view” refers to the page that is seen, and “viewmodel” isMVVM
At the heart of it is connectivityView
withModel
The bridge,implementationview
Is automatically updated toviewModel
,viewModel
Changes in will also automatically appear inview
on, it is a kind ofData-driven viewThe model
The difference between:
MVC
In theControl
inMVVM
Translated intoviewModel
MVVM
The view is displayed through data, not through node operationsMVVM
Basically solved the problemMVC
In a large number ofDOM
The 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:
Vue
Through data hijacking with a publisher-subscriber design pattern, internally through invocationobject.defineProperty()
To hijack the propertiesgetter
andsetter
, 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, using
Object.defineProperty()
I’m going to add to the propertiesgetter
andsetter
If you assign a value to an object, it will triggersetter
, so you can listen for data changes - Implement a parser “Compile” : parse
Vue
Template 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” :
Watcher
The subscriber isObserver
andCompile
Between the communication bridge, the main task is subscriptionObserver
The parser is triggered when a message about a property value change is receivedCompile
The corresponding update function in - Implement a subscriber “Dep” : The subscriber uses a publish-subscribe design pattern to collect subscribers
Watcher
, to the listenerObserver
And the subscriberWatcher
Unified 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 example
vm.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...
) Vue
willdata
The array in which the prototype chain is rewritten points to the array prototype method defined by itself when calling the array’sAPI
If 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 directly
splice
Method 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 called
defineReactive()
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.defineProperty
You can only hijack the properties of an object, so you need to traverse every property of the object, whileProxy
Objects can be directly representedObject.defineProperty
The new attributes need to be observed manually becauseObject.defineProperty
It 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.defineProperty
This is the reason why we are givingdata
To add properties to an array or object in$set
So that the view can be updated)Proxy
High performance. Supports 13 interception modes
What are the pros and cons of the virtual Dom?
Advantages:
- Guaranteed performance limits: virtualisation of the framework
Dom
Need to adapt some of its operations to any upper-level API that may be generatedDom
The implementation of the operation must be universal, so its performance is not optimal, but it is more violentDom
The operation is much better, thus ensuring a lower limit on performance - No manual operation
Dom
: The framework will be based on the virtualDom
Two-way binding with data to help us update views and improve development efficiency - Cross-platform: Virtual
Dom
Essentially,JavaScript
Object, but realDom
And platform related, compared to virtualDom
It 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:
- with
JavaScript
Object simulation realityDom
Tree, to the realDom
abstract - through
diff
Algorithm for two virtualDom
Object to compare - through
patch
The algorithm will make two virtualDom
Object differences apply to realityDom
The tree
How does nextTick work? What’s the role in Vue
- Principle:
EventLoop
Event 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 function
callback
Instead 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 time
dom
A 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 beforecreated
→ 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/event
Event callback- But not here
$el
- Data observation (
beforeMount
→ Called before the mount begins, relevantrender
Function is called for the first timemounted
→$el
Newly createdvm.$el
Replace, and then mount it to the instancebeforeUpdate
→ Data update when called, occurs in virtualDOM
Re-render and patch beforeupdated
→ Virtual due to data changesDOM
Re-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 usabledestroyed
→Vue
Called after instance destruction. When this hook is called,Vue
Everything 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 requestmounted
→ The instance has been mounted, you can do someDOM
operationbeforeUpdate
→ You can further change the state in this hook without triggering additional renderingupdated
→ Can be executed depending onDOM
In the operation. In most cases, however, you should avoid changing the state in this hook, as this can result in an infinite loop of updatesdestroyed
→ 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
activated
And in the<keep-alive>
Use this hook when the component is activateddeactivated
And 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
- in
vue
In, the parent component can passprop
Pass the data to the child component, but thisprop
It 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
$emit
The 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:
vuex
The state store of is reactive. whenvue
Components fromstore
, ifstore
Changes in the state of, and the corresponding components are efficiently updated- You can’t change it directly
store
Change the state ofstore
The 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-if
The node where the current instruction resides will not be rendered if the condition is not trueDom
Element, the event listener and child components of the conditional block are destroyed and rebuilt during the switchv-show
Only based oncss
Toggle 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?
computed
Is 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)watch
When 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
- in
sum
Reactive properties are read the first time you evaluate themcount
To collect this responsive data as a dependency. And compute a value to store in its ownvalue
On,dirty
Set it to false and then access it in the templatesum
I just return this valuevalue
Is not re-evaluated. - 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.
- 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-alive
Has two separate life cycles (activated
|deactivated
),keep-alive
The components of the package are not destroyed when switched, but are cached in memory and executeddeactivated
Hook, gets memory when switching back to component, executes after renderingactivated
hook- provide
include
andexclude
Property, both support strings or regular expressionsinclude
Indicates that only components with matching names will be cachedexclude
Indicates that any component with a matching name will not be cachedexclude
Priority 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.capture
Event 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 page
JavaScript
.Css
Unified 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
- The first loading is time-consuming (to achieve the function and display effect of a single-page Web application, you need to load the page
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?
route
Represents a route information object, includingpath
.params
.hash
.query
.fullPath
.matched
.name
Routing information parametersrouter
Represents 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 component
beforeRouteLeave
Leave the guards - Call global
beforeEach
The guards - Called in a reused component
beforeRouteUpdate
The guards - Called in the routing configuration
beforeEnter
The guards - Resolve the asynchronous routing component
- Called in an activated component
beforeRouteEnter
The guards - Call global
beforeResolve
The guards - Navigation confirmed
- Call global
afterEach
The guards - The trigger
Dom
update - Called with the created instance
beforeRouteEnter
Guard passnext
The callback
What is the difference between the hash/History modes on the VUe-Router?
hash
Model will beurl
Displays ‘#’ on thehistory
Model does not- When you refresh the page,
hash
The mode can be loaded normally tohash
Value corresponds to the page,history
If 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,
hash
Mode can support earlier versions of browsers and IE
How is hash/history implemented in vue-Router?
hash
model#
behindhash
Value 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 listeninghashchange
Events can be knownhash
What has changed. According to thehash
Changes to implement partial updates to the page
history
modelhistory
The implementation of the pattern, mainlyHtml5
The two apis published by the standard (pushState
andreplaceState
), these two apis can be changedurl
, but will not send the request, so you can listenurl
To implement local updates
How to define dynamic routes for vue-router? How do I get the value passed in
- Dynamic routing is created by using
path
Property, 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.params
So you can get dynamic parameters from this property
this.$route.params.id
Copy the code
What are the parameter transmission modes of vue-router?
- through
params
- Can only use
name
And don’t usepath
- The parameter will not be displayed in
url
on - Browser force refresh will clear the parameters
- Can only use
- through
query
- Can only use
path
And don’t usename
name
You can usepath
The path- The parameters will be displayed in
url
on - The parameters are not cleared when the browser is refreshed
- Can only use
“About Vuex”
What are the pros and cons of VUEX?
- advantages
- Addresses messaging for non-parent components (storing data in
state
C) - To reduce the
Ajax
Request times, some scenarios can be directly from memoryState
To obtain
- Addresses messaging for non-parent components (storing data in
- disadvantages
- Refresh the browser,
vuex
In theState
It will go back to the initialized state
- Refresh the browser,
What are the properties of VUex?
State
:vuex
Basic data used to store variablesGetter
: From basic datastate
Derived data, equivalent tostate
Calculated properties ofMutation
: The method for submitting updated data, which must be synchronous (used if asynchronous is required)action
). eachmutation
Both have a string event type (type
) and a callback function (handler
)Action
And:mutation
Is basically the same, but the difference isaction
Is submittedmutation
Instead of changing the state directlyaction
Any 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?
vuex
It’s a repository, and the repository is filled with a lot of objectsstate
That’s where the data source isstate
The data stored in it is responsive,Vue
Components fromstore
, if yesstore
The components that depend on the data are also updated- It does this by
mapState
The globalstate
andgetters
Mapped to the current componentcomputed
Compute attributes
What are the features of getters in Vuex?
getters
Can bestate
To do the computation, you can view it asstore
thecomputed
Calculate attribute- It is possible to compute properties in components, but
getters
It can be reused across multiple components - If a state is only used within a component, it is not required
getters
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 in
vuex
thestate
In the - If reused elsewhere, the request can be placed in
action
In, easy to reuse; If you do not need to reuse this request, write it inVue
It’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 to
SPA
The content of the page is throughAjax
While search engine crawl tools do not waitAjax
Asynchrony is completed before grabbing the page content, so inSPA
The page is not crawled throughAjax
The content obtained; whileSSR
The 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) :
SPA
Will wait for allVue
The compiledJs
After 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. whileSSR
Directly rendered by the server page directly back to display, without waiting for downloadJs
File before rendering, soSSR
There are faster content arrival times
Disadvantages of server-side rendering SSR:
- More development conditions: for example, server-side rendering is only supported
beforeCreate
.created
Lifecycle 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 serverSPA
The server rendering application needs to be inNodeJs
Operating in the environment - More server load: in
NodeJs
The rendering of a complete application would obviously be better than just providing static filesserver
Consumes more CPU resources