1. Simply talk about vue
- Vue is a gradual framework, add functions according to your needs
- Vue data driver adopts mvvm mode, m is the data layer, v is the view layer, and vm is the scheduler
- SPA single page application, only one page, fast loading rate
- Componentization, strong reusability
So, what are its disadvantages?
- The bottom layer of vue2 is responsive based on Object.defineProperty. This api itself does not support IE8 and below browsers
- Inborn deficiency of csr, first screen performance problem (white screen)
- Because search engine crawlers such as Baidu cannot crawl the content in js, spa is inherently lacking in seo optimization (Google's puppeteer is pretty awesome, and this tool is also used to implement the pre-rendering bottom layer)
2. The difference between vuehereact
First of all, you have to talk about the same points, both are MVVM frameworks, data-driven views, no dispute. If it is different, it may be divided into the following points:
- Vue is a complete set of officially maintained frameworks. The core libraries are mainly maintained by You Yuxi God alone, while react is maintained by shameless books (many libraries are maintained by the community). For a while, many people questioned the follow-up maintainability of vue , It seems that this is not the problem.
- Vue is easy to get started, an advanced framework. In the vernacular, you can learn a little and use a little in your project. You don’t necessarily need to learn the whole vue at once to use it. React, I’m afraid you will face it. The project is helpless.
- Grammatically, vue does not restrict you to write pages in es6+ full js format. View and js logic can be separated as much as possible, reducing the disgusting nesting of react-jsx that many people cannot understand. After all, they are front-end developers or are more accustomed to html is clean.
- Many people say that react is suitable for large-scale projects and what is suitable for them. Vue is lightweight and suitable for small and medium-sized mobile projects. In fact, I want to say that people who say this are not compelling at all. Vue can handle complex large-scale applications. , Or even say that if you don’t learn React very well, what you write may not be as good as Vue’s. After all, Vue can follow the official documentation, and someone can help you standardize it. React is lazy and free, and you can play freely.
- Vue is obviously more popular in China than react, which is largely due to its many grammars, including programming thinking, which are more in line with Chinese thinking
1. What is mvvm
The core of MVVM is the data driver that is ViewModel, and
ViewModel
relationship mapping between View and Model.
The essence of MVVM is to operate view
data and then operate
DOM
. With the help of MVVM no need to directly manipulate the DOM. Developers only need to write
ViewModel
in , making the View fully automated by
.
2. What is a SPA single page, and what are its advantages and disadvantages
SPA (single-page application) that is A web project
has only one page (that is, an HTML file, and the transformation of HTML content is realized by the routing mechanism.
Only when the Web page initialized,
loads the corresponding
HTML, JavaScript and CSS. Once the page
loaded, SPA
not because the user's
operation carried out pages
reload or jump; instead of using
routing mechanism to implement HTML
content transformation, UI interaction with the user, to avoid re page load.
advantages:
user experience is good and fast, the content change does not need to reload the entire page, avoiding unnecessary jumps and repeated rendering;
- Based on the above point, SPA has relatively little pressure
server;
- Front-end and back-end
separate responsibilities,
clear architecture, the front-end carries out interaction logic, and the back-end is responsible for data processing;
Disadvantages :
initial loading takes a lot of time: In order to realize the single-page Web application function and display effect, JavaScript and CSS need to be loaded uniformly when the page is loaded, and some pages are loaded on demand;
Forward and Backward Routing Management: Since a single-page application displays all content on one page, the browser’s forward and backward functions cannot be used, and all page switching needs to build stack management by themselves;
SEO is more difficult: Because all the content is dynamically replaced and displayed on one page, it has a natural weakness in SEO.
3. Life Cycle
3-1 Basic concepts
What is the vue life cycle? The process of Vue instance creation from to destruction is the life cycle.
Note : browser has 8 hook, but node
to do server-side rendering when only beforeCreate
and created
- beforeCreate is
new Vue()
triggered afterfirst hook, data, methods, computed data and methods and not on the watch can be accessed at the current stage. Can do page interception. When entering a route, we can judge whether there is permission to enter, whether it is safe to enter, whether the carrying parameters are complete, and whether the parameters are safe. When using this hook function, it avoids the page to judge and saves the creation of a Vue instance.
- created occurs after the
instance is created, the current stage has completed the
data observation, that is, you can use the data, change the data, here
changes the data
will not trigger the
updated
function. You can do some initial data acquisition. In the current stage,cannot interact with
Dom
(because the Dom has not been created). If you have to, you can access the Dom
vm.$nextTick
- beforeMount occurs before
mounted, before the template template has been imported into the rendering function to compile. In the current stage, the
virtual Dom has been created for
, and rendering will begin soon. You can also make changes to the data at this time without triggering updated.
- Mounted occur
after the mount is completed, at this stage,
real
Dom
mount is completed, the data is completedway binding, can
access to Dom
node, using the property for $ refs Dom operate.
- beforeUpdate occurs before
updated, that is, the responsive data is updated, and the virtual dom is triggered before re-rendering. You can change the data in the current stage without causing re-rendering.
- updated occurs after the update of
completed, the current stage component Dom has been updated. It should be noted to avoid changing the data during this period, as this may cause an endless loop of updates.
- beforeDestroy occurs before the
instance is destroyed. In the current stage, the instance is fully usable, and we can do the finishing touches at this time, such as clearing the timer and destroying the parent component’s repeated monitoring of the child component.
beforeDestroy(){Bus.$off("saveTheme")}
- destroyed occurs after the instance is destroyed, at this time only the dom shell is left. The component has been disassembled, the data binding has been removed, the monitor has been removed, and all sub-instances have been destroyed.
3-2 Life Cycle Calling Sequence
- The calling order of the components is first parent and then child
- The order in which the rendering is completed is first child then parent
- The destruction operation of the component is first parent and then child
- The order of completion of the destruction is the first son and then the father
load the rendering process parent beforeCreate->parent created->parent beforeMount->child beforeCreate->child created->child beforeMount->child mounted->parent mounted
child component update process parent beforeUpdate->child beforeUpdate->child updated->parent updated
parent component update process parent beforeUpdate -> parent updated
destruction process parent beforeDestroy->child beforeDestroy->child destroyed->parent destroyed
3-3 What is the role of vue life cycle
There are multiple event hooks in its life cycle, let us control the Vue instance process
more clearly.
3-4 Which hooks will be triggered on the first page load
The beforeCreate, created, beforeMount, mounted hooks are triggered when the page is loaded for the first time
3-5 Which scenarios are suitable for each cycle
- beforecreate: You can add a loading event here to trigger when the instance is loaded
- created: the event when the initialization is completed is written here, if the loading event ends here, asynchronous requests are also suitable to be called here
- mounted: Mount the element and get the DOM node
- updated: If the data is processed uniformly, write the corresponding function here
- beforeDestroy: can clear the timer
- nextTick: Operate the dom immediately after updating the data
4. The difference between v-show and v-if
v-if
- It is true conditional rendering, because it will ensure that the
event listener and
subcomponents in the conditional block are
destroyed and rebuilt by 160c32d2df2481 during the switching process;
is also lazy: if the condition is false in the initial rendering, nothing is done-the conditional block will not be rendered until the condition becomes true for the first time.
v-show
No matter what the initial conditions are, the element will always be rendered, and it is simply switched based on the CSS "display" property.
So:
- v-if is suitable for
rarely changes conditions during runtime, and
does not need to switch conditions frequently;
- v-show is suitable for scenarios that
switch conditions very frequently.
5. Vue's one-way data flow
background:
form a 160c32d2df256d single downward binding between their parent and child props: updates to the parent prop will flow down to the child components, but not the other way around. This will prevent the child component
accidentally changing the state of the parent component, which will cause the data flow of your application to become chaotic.
Every time the parent component is updated, all props in the child component will be refreshed to the latest value. This means that you should not change props inside a subcomponent. If you do this, Vue will issue a warning in the browser console. When the child component wants to modify, it can only dispatch a custom event
$emit
. After the parent component receives it, it can be modified .
has two common attempts to change a prop:
- This prop is used to pass an initial value;
- Next, this subcomponent hopes to use it as a local prop data.
In the second case, it is better to define a local data attribute and use this prop as its initial value:
props: ['initialCounter'],
data: function () {
return {
counter: this.initialCounter//定义本地的data属性接收prop初始值
}
}
This prop is passed in as a primitive value and needs to be converted.
In this case, it is best to use the value of this prop to define a calculated property
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}
6. In which life cycle is an asynchronous request suitable for invocation?
The asynchronous request of the official instance
mounted
, but it can also be called during the created life cycle.
I recommend calling asynchronous requests in the created hook function, which has the following advantages:
can get
server data faster,
reduces page loading time;
ssr
does not support beforeMount and mounted hook functions, so putting it in created helps consistency;
7. What are the communication methods of Vue2.x components?
7-1 Parent-child component communication
- Parent -> child props; child (emit) -> parent (on)
- Get the parent-child component instance $parent / $children For example: write directly in the methods method of the child component: this.$parent.show()//show is the method defined in the parent component
- Ref (if used on ordinary DOM elements, the reference points to the DOM element; if used on sub-components, the reference points to the component instance), such as mounting one on the label of the imported sub-component: ref="comA" , And then in the method or sub-component data, this.$refs.comA.titles
- Provide and inject are not officially recommended, but they are commonly used when writing component libraries. The ancestor component uses the provider to provide variables, and then injects the variables in the descendant components.
7-2 Brother component communication
- Event Bus realizes cross-component communication: Vue.prototype.$bus = new Vue
- Vuex
7-3 Cross-level component communication
- Vuex
- attrs,listeners
- Provide、inject
7-4 Use
1. Father and son props, on
// Subassembly
<template>
<header>
<h1 @click="changeTitle">{{title}}</h1>//绑定一个点击事件
</header>
</template>
<script>
export default {
data() {
return {
title:"Vue.js Demo"
}
},
methods:{
changeTitle() {
this.$emit("titleChanged","子向父组件传值");//自定义事件 传递值“子向父组件传值”
}
}
}
</script>
// parent component
<template>
<div id="app">
<Header @titleChanged="updateTitle" ></Header>//与子组件titleChanged自定义事件保持一致
<h2>{{title}}</h2>
</div>
</template>
<script>
import Header from "./Header"
export default {
data(){
return{
title:"传递的是一个值"
}
},
methods:{
updateTitle(e){ //声明这个函数
this.title = e;
}
},
components:{
Header
}
}
</script>
2. parent / $children and ref
// A subcomponent
export default {
data () {
return {
title: 'a组件'
}
},
methods: {
sayHello () {
alert('Hello');
}
}
}
// parent component
<template>
<A ref="comA"></A>
</template>
<script>
export default {
mounted () {
const comA = this.$refs.comA;
console.log(comA.title); // a组件
comA.sayHello(); // 弹窗
}
}
</script>
3.attrs,listeners
attrs: contains parent scope in
not prop the
identified (and obtain) the binding properties (except for class and style). When a component does not declare any props, all bindings of the parent scope (except class and style) will be included here, and internal components can be passed in via v-bind="$attrs". Usually used with the inheritAttrs option.
listeners: Contains v-on event listeners in the parent scope (without the .native decorator). It can pass in internal components via v-on="$listeners"
// index.vue
<template>
<div>
<h2>浪里行舟</h2>
<child-com1 :foo="foo" :boo="boo" :coo="coo" :doo="doo" title="前端工匠"></child-com1>
</div>
</template>
<script>
const childCom1 = () => import("./childCom1.vue");
export default {
components: { childCom1 },
data() {
return {
foo: "Javascript",
boo: "Html",
coo: "CSS",
doo: "Vue"
};
}
};
</script>
// childCom1.vue
<template class="border">
<div>
<p>foo: {{ foo }}</p>
<p>childCom1的$attrs: {{ $attrs }}</p>
<child-com2 v-bind="$attrs"></child-com2>
</div>
</template>
<script>
const childCom2 = () => import("./childCom2.vue");
export default {
components: {
childCom2
},
inheritAttrs: false, // 可以关闭自动挂载到组件根元素上的没有在props声明的属性
props: {
foo: String // foo作为props属性绑定
},
created() {
console.log(this.$attrs); // 父组件中的属性,且不在当前组件props中的属性。{ "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
}
};
</script>
// childCom2.vue
<template>
<div class="border">
<p>boo: {{ boo }}</p>
<p>childCom2: {{ $attrs }}</p>
<child-com3 v-bind="$attrs"></child-com3>
</div>
</template>
<script>
const childCom3 = () => import("./childCom3.vue");
export default {
components: {
childCom3
},
inheritAttrs: false,
props: {
boo: String
},
created() {
console.log(this.$attrs); // / 父组件中的属性,且不在当前组件props中的属性。{"coo": "CSS", "doo": "Vue", "title": "前端工匠" }
}
};
</script>
// childCom3.vue
<template>
<div class="border">
<p>childCom3: {{ $attrs }}</p>
</div>
</template>
<script>
export default {
props: {
coo: String,
title: String
}
};
</script>
4. Use of Provide and inject:
Parent component
<template>
<div id="app">
</div>
</template>
<script>
export default {
data () {
return {
datas: [
{
id: 1,
label: '产品一'
}
]
}
},
provide {
return {
datas: this.datas
}
}
}
</script>
Subassembly
<template>
<div>
<ul>
<li v-for="(item, index) in datas" :key="index">
{{ item.label }}
</li>
</ul>
</div>
</template>
<script>
export default {
inject: ['datas']
}
</script>
8. What is SSR
SSR is server-side rendering, that is, Vue will render tags HTML
on the client side to complete the work on the server side, and then html directly to the client side.
The advantages and disadvantages of server-side rendering SSR are as follows:
(1) Advantages of server-side rendering:
- Better SEO : Because the content of the SPA page is obtained through Ajax, and the search engine crawler does not wait for the asynchronous completion of Ajax to crawl the page content, so in
SPA
,not crawl the page through
Ajax
acquiredcontent; and
SSR
directly by thereturn the server
has been good for rendering the page (data already included in the page), so the search engines crawling tool can capture the rendered page;
- faster content arrival time (fold faster loading):
SPA
willwait for all Vue compiled
js
fileAfter all the download is complete,
before starting the page
rendering, file downloads, will take some time , So the first screen rendering takes a certain amount of time; SSR is directly rendered by the server and the page is directly returned to the display, without waiting for the download of js files and rendering, so SSR has a faster content arrival time;
(2) Disadvantages of server-side rendering:
- More development conditions limit : For example, server-side rendering only supports
beforCreate
andcreated
, which will cause some external extension libraries to require special processing to run in server-side rendering applications; and can be deployed in any The completely static single-page application SPA on the static file server is different. The server-side rendering application needs to be in the Node.js server running environment; - More server load : Rendering a complete application in Node.js will obviously consume a lot of CPU resources (CPU-intensive) than a server that only provides static files, so if you expect it in a high-traffic environment (high traffic), please prepare the corresponding server load, and use the caching strategy wisely.
9.Vue routing
9-1 How many routing modes are there in vue-router?
vue-router has 3 routing modes: hash
, history
, abstract
, the corresponding source code is as follows:
switch (mode) {
case 'history':
this.history = new HTML5History(this, options.base)
break
case 'hash':
this.history = new HashHistory(this, options.base, this.fallback)
break
case 'abstract':
this.history = new AbstractHistory(this, options.base)
break
default:
if (process.env.NODE_ENV !== 'production') {
assert(false, `invalid mode: ${mode}`)
}
}
routing mode is as follows:
- hash : Use URL hash value for routing. Support all browsers
, including those that do not support HTML5 History Api;
- history : Rely on HTML5 History API and server configuration. You can view the HTML5 History mode for details;
- abstract : Support all
JavaScript
operating environments, such as Node.js server. If it is found that there is no browser API, the router will automatically be forced to enter this mode.
9-2 Implementation Principles of Hash Routing and History Routing
(1) The realization principle of hash mode
The early implementation of front-end routing was based on location.hash
. The implementation principle is very simple, the value of location.hash is the content after # in the URL.
For example, for the following website, its location.hash value is '#search'
:
https://www.word.com#search
The implementation of hash routing mode is mainly based on the following characteristics:
- The hash value in the URL is only a
state of the
client, which means that when a request is made
, the hash part
will not be sent;
- Changes to
hash value will add a
record to
in the browser's
access history. Therefore, we can control the switching of hash through the browser's back and forward buttons;
- You can use the a tag and set the href attribute. When the user clicks on this tag, the hash value of the URL will change; or use JavaScript to assign a value to loaction.hash to change the hash value of the URL;
- We can use the
hashchange
event to monitor the change of the hash value to jump (render) the page.
(2) The realization principle of history mode
HTML5 provides History API
to implement URL changes. The main APIs are as follows:
- history.pushState() //new history
- history.repalceState(). //Replace history
Both API can without performing refresh,
operation of the browser
history. The only difference is that the former is to add a new history record, and the latter is to directly replace the current history record, as shown below:
window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);
history routing mode is mainly based on the following features:
- PushState and repalceState two APIs to operate and realize URL changes;
- We can use the
popstate
event to monitor the changes of the url, so as to jump (render) the page; - History.pushState() or history.replaceState() will not trigger the popstate event, then we need to manually trigger the page jump (rendering).
10. What is the function of the key in Vue?
The key is the unique mark vnode
of Vue. With this key, our
diff
operation can be more accurate and faster.
Vue's diff process can be summarized as:
oldCh
and newCh
have two variables head and tail
oldStartIndex、oldEndIndex
and newStartIndex、newEndIndex
, they will be old and new nodes nodes will be twenty-two contrast, ie a total of 4 COMPARATION way : newStartIndex and oldStartIndex, newEndIndex and oldEndIndex, newStartIndex and oldEndIndex , NewEndIndex and oldStartIndex, if none of the above four comparisons
match, if
key
is set, the key will be used for comparison. During the comparison, the traversal will
toward the middle of 160c32d2df2fa7. Once StartIdx> EndIdxCh indicates oldCh and new At least one has been traversed, and the comparison will end.
So the role of the : key is the only mark of vnode in Vue, through this key, our diff operation can be more accurate and faster
- It is more accurate because the key is not reused in place. In the comparison of the sameNode function a.key === b.key, the situation of in-situ reuse 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. The source code is as follows:
function createKeyToOldIdx (children, beginIdx, endIdx) { let i, key const map = {} for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key if (isDef(key)) map[key] = i } return map }
Reference 1: Vue2.0 v-for: What is the use of key?
11. Principles of Virtual DOM Implementation
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.
13. Advantages and disadvantages of virtual DOM
Advantages:
- ensure the performance limit : virtual DOM framework needs to adapt any action that may arise upper API, some of
implement DOM operations must be
universal, so its performance is not optimal; but compared rude The performance of DOM operation is much better, so the virtual DOM of the framework can at least guarantee that
can
provide good
performance, that is, the lower limit of guaranteed performance, if you do not need to manually optimize 160c32d2df315a;
- No need to manually manipulate the DOM : We no longer need to manually manipulate the DOM, only need to write the code logic of the View-Model, the framework will bind the virtual DOM and the data in both directions, helping us to update the view in a predictable way, which is great Improve our development efficiency;
- Cross-platform : The virtual DOM is essentially a JavaScript object, and the DOM is strongly related to the platform. In contrast, the virtual DOM can perform more convenient cross-platform operations, such as server rendering, weex development, and so on.
Disadvantages:
- cannot be optimized for extreme : Although virtual DOM + reasonable optimization is sufficient to meet the performance requirements of most applications, in some applications with extremely high performance requirements, virtual DOM cannot be optimized for targeted extremes.
14. Comparison of pros and cons between Proxy and Object.defineProperty
Proxy are as follows:
- Proxy can directly monitor objects instead of attributes;
- Proxy can directly monitor the changes of the array;
- Proxy has as many as 13 interception methods, not limited to apply, ownKeys, deleteProperty, has, etc. Object.defineProperty does not have;
- Proxy returns a new object, we can only manipulate the new object to achieve the goal, while Object.defineProperty can only traverse the object properties and modify them directly;
- Proxy as a new standard will be subject to continuous performance optimization by browser manufacturers, which is the performance bonus of the legendary new standard;
Object.defineProperty are as follows:
- Good compatibility, support IE9, but Proxy has browser compatibility issues, and it cannot be smoothed with polyfill
14-1 So, what function can Proxy achieve?
Proxy is a new feature in ES6, which can be used to customize operations in objects.
let p = new Proxy(target, handler)
- target represents the object that
add a proxy
- The handler is used to customize the
operation in
object, for example, it can be used to customize the set or get function.
Let's implement a data response style through Proxy:
let onWatch = (obj, setBind, getLogger) => {
let handler = {
get(target, property, receiver) {
getLogger(target, property)
return Reflect.get(target, property, receiver)
},
set(target, property, value, receiver) {
setBind(value, property)
return Reflect.set(target, property, value)
}
}
return new Proxy(obj, handler)
}
let obj = { a: 1 }
let p = onWatch(
obj,
(v, property) => {
console.log(`监听到属性${property}改变为${v}`)
},
(target, property) => {
console.log(`'${property}' = ${target[property]}`)
}
)
p.a = 2 // 监听到属性a改变为2
p.a // 'a' = 2
In the above code, by customizing the set and get functions, we have inserted our function logic into the original logic, so that a notification is issued when any property of the object is read or written.
Of course, this is a simple version of reactive implementation. If you need to implement a reactive approach in Vue, you need to collect dependencies in get and distribute updates in set. The reason why Vue3.0 uses Proxy to replace the original API is because Proxy does not require a layer Layer recursion adds a proxy for each attribute, and the above operations can be completed at one time. The performance is better, and the original implementation has some data updates that cannot be monitored, but the Proxy can perfectly monitor data changes in any way. The only flaw is the browser. The compatibility is not good.
15. How does the Vue framework implement the monitoring of objects and arrays?
The Vue framework traverses arrays and recursively traverses objects, so that Object.defineProperty() can also be used to monitor objects and arrays (operations of some methods).
vue2:
array is to use
object.defineProperty
to redefine each item in the array. The seven methods that can cause the array to change are
pop 、 push 、 shift 、 unshift 、 splice 、 sort 、 reverse
. As long as these methods are executed to change the content of the array, the content will be updated.
- It is used to hijack the
rewrites the array method. Specifically, it changes the prototype of the array and changes it to its own. When the user adjusts some methods of the array, he takes his own method, and then informs the view to update (The essence is that the method of updating data is called on the original method).
- The array item may be a
object, then observe each item of the array
vue3:
Use proxy instead, you can directly monitor the changes in the object array.
16.How does Vue achieve two-way data binding
Vue data two-way binding mainly refers to : data changes update view, view changes update data
When the content of the input box changes, the data in Data changes synchronously. That is, the change of View => Data. When the data in Data changes, the content of the text node changes synchronously. That is, the change of Data => View.
Among them, View changes to update Data can be achieved through event monitoring, so the work of Vue's two-way data binding is mainly how to update View according to Data changes.
two-way data binding through the following 4 steps:
- implements a listener Observer to traverse the data object, including the attributes of the sub-attribute objects, use
Object.defineProperty()
setter
andgetter
to the attributes. In this case, assigning a value to this object will trigger the setter, and then the data change can be monitored. - implements a parser Compile to parse the Vue template instructions, replace
variables
data, and then initialize the rendering page view, and bind the update function to the node
instruction, and add a subscription for monitoring data Or, once the data changes, receive a notification and call the update function to update the data.
- realizes a subscriber Watcher Subscriber is the communication bridge between Observer and Compile. The main task is to subscribe to the message of property value change in Observer. When the message of property value change is received, the corresponding one in the parser Compile is triggered Update function.
- implements a subscriber Dep The subscriber adopts a publish-subscribe design model to collect subscriber watchers, and perform unified management of listener Observer and subscriber Watcher.
17. The principle of v-model
The v-model command creates two-way data binding on elements such as form input, textarea, select, etc. v-model is essentially syntactic sugar, which uses different attributes for different input elements internally and throws different events:
- The text and textarea elements use the
value
attribute and theinput
event; checked
and radio use 060c32d2df3637 attribute andchange
event;- The select field has value as
prop
andchange
as event.
Take the input form element as an example :
<input v-model='something'>
Equivalent to
<input :value="something" @input="something = $event.target.value">
18. Why is data in the component a function?
Why must the data in the component be a function and then return an object, while in the new Vue instance, data can be an object directly?
// data
data() {
return {
message: "子组件",
childName:this.name
}
}
// new Vue
new Vue({
el: '#app',
router,
template: '<App/>',
components: {App}
})
If a component is reused multiple times, multiple instances will be created. Essentially, these instances use the same constructor.
If data is an object, the object is a reference type and will affect all instances. Therefore, in order to ensure that data does not conflict between different instances of the component, data must be a function.
The instance of new Vue will not be reused, so there is no problem of referencing objects.
19. Talk about your keep-alive
a keep-alive Vue built a
component, it can be
component contains
hold,
avoid re-rendered, which has the following characteristics:
- Generally used in conjunction with routing and dynamic components for caching components;
- Provide
include
andexclude
properties, both of which are supported by strings or regular expressions, include only the name representscomponent match will be
cache, exclude represents any name
components are matched
not be cached, which exclude the
priority The level is higher than include
;
- Corresponding to the two hook functions
activated
anddeactivated
, when the component is activated, the hook function activated is triggered, and when the component is removed
, the hook function deactivated is triggered.
keep-alive life cycle
- activated: When the page is first entered, the hook trigger sequence is created->mounted->activated
- deactivated: deactivated will be triggered when the page exits, and only activated will be triggered when forward or backward again
20. Can the parent component monitor the life cycle of the child component?
For example, there are parent components Parent and child components Child. If the parent component monitors that the child component is mounted, it will do some logical processing, which can be achieved by the following writing:
// Parent.vue
<Child @mounted="doSomething"/>
// Child.vue
mounted() {
this.$emit("mounted");
}
The above needs to manually trigger the event of the parent component through $emit. A simpler way can be to listen through @hook when the parent component references the child component, as shown below:
// Parent.vue
<Child @hook:mounted="doSomething" ></Child>
doSomething() {
console.log('父组件监听到 mounted 钩子函数 ...');
},
// Child.vue
mounted(){
console.log('子组件触发 mounted 钩子函数 ...');
},
// The above output sequence is:
// The child component triggers the mounted hook function...
// The parent component listens to the mounted hook function...
Of course, the @hook method can not only monitor mounted, but also other life cycle events, such as created, updated, etc. can also be monitored.
21. If you assign a value to an array item directly, can Vue detect the change?
Due to JavaScript limitations, Vue cannot detect the following array changes:
- When you use the index to directly set an array item, for example:
vm.items[indexOfItem] = newValue
- When you modify the length of the array, for example:
vm.items.length = newLength
In order to solve the first problem, Vue provides the following operation method:
// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// vm.$set (an alias of Vue.set)
vm.$set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
In order to solve the second problem, Vue provides the following operation method:
// Array.prototype.splice
vm.items.splice(newLength)
22. How to monitor array changes in vue2.x
Using function hijacking manner,
rewrite method of the array, the Vue
data
in array of
prototype chain rewritten, pointing
own definition
array prototyping. In this way, when the array api is called, the dependency update can be notified. If the array contains reference types, the reference types in the array will be recursively traversed again to monitor. This realizes the monitoring of array changes.
22. The diff algorithms of Vue2.x and Vue3.x renderers are respectively talked about
Simply put, the diff algorithm has the following process
Compare at the same level, and then compare the child nodes, first determine that one party has child nodes and the other has no child nodes (if the new children have no child nodes, remove the old child nodes)
Compare the case where there are child nodes (core diff) Recursively compare child nodes
The time complexity of the normal Diff two trees is O(n^3), but in reality, we rarely do cross-level mobile DOM, so Vue optimizes the Diff from O(n^3) -> O(n), only when the old and new children are multiple child nodes, the core Diff algorithm needs to be compared at the same level.
The core Diff algorithm of Vue2 double-ended comparison algorithm. At the same time, the comparison is started from the two ends of the old and new children, and the reusable node is found with the help of the key value, and then related operations are performed. Compared with React's Diff algorithm, it can reduce the number of mobile nodes in the same situation, reduce unnecessary performance loss, and be more elegant.
Vue3.x draws on the ivi algorithm and the inferno algorithm to determine the type of VNode when it is created, and uses bit operations to determine the type of a VNode during the mount/patch process. On this basis, cooperate with the core Diff algorithm , Which makes the performance improved compared with Vue2.x. The algorithm also uses the idea of dynamic programming to solve the longest recursive subsequence.
23. Vue template compilation principle
Simply put, the compilation process of Vue is the process of converting template into render function. Will go through the following stages:
- Generate AST
- Tree optimization
- codegen
First, parses the template and generates
AST
syntax tree (a form of JavaScript object to describe the entire template).
Use a lot of regular expression
template
resolve encountered
label,
when the text will
perform the corresponding
hook performs the correlation process.
Vue data is responsive, but in fact, not all data in the template is responsive. There are some data after the first rendering
will not
change, corresponding
DOM
will not change. Then the optimization process is depth traversing the AST tree, in accordance with the relevant conditions of
tree nodes
mark. These are labeled
node (static nodes) we can
skip their
comparison, has played a significant role in optimizing the template at runtime.
The last step of compilation is to convert the optimized AST tree into
executable
code.
24.Computed and Watch
computed:
- computed is the
calculated attribute, that is, the calculated value, which is more used in the scenario of calculating the value
- Computed has
value will be cached after the getter is executed. Only after the attribute value it depends on changes, the next time the computed value is obtained will the corresponding getter be called again for calculation
- Compute is suitable for computing scenarios that consume more performance
watch:
- More is the role of ``observation'', similar to the monitoring callback of some data, used to observe
props
$emit
or. When the data changes, the callback is executed for subsequent operations.
- No cache of the page re-rendering time when
no change will
execution
Summary:
- When we want to perform numerical calculations and rely on other data, then design this data as computed
- If you need to do something when a certain data changes, use watch to observe the data change
25.nextTick
In next
DOM
after the update cycle execution
delayed callback. The code inside will wait until
dom is updated before executing.
<template>
<section>
<div ref="hello">
<h1>Hello World ~</h1>
</div>
<el-button type="danger" @click="get">点击</el-button>
</section>
</template>
<script>
export default {
methods: {
get() {
}
},
mounted() {
console.log(333);
console.log(this.$refs['hello']);
this.$nextTick(() => {
console.log(444);
console.log(this.$refs['hello']);
});
},
created() {
console.log(111);
console.log(this.$refs['hello']);
this.$nextTick(() => {
console.log(222);
console.log(this.$refs['hello']);
});
}
}
</script>
26. Vue responsive principle
26-1 Vue2.x Responsive Data Principle
When Vue initializes the data, it uses Object.defineProperty
to redefine all the attributes in the data. When the page
uses the corresponding attributes, it will first perform the
dependency collection (collect the watcher of the current component). If the attribute changes
, it will notify the dependent dependency
Perform
update operation (publish and subscribe)
specific process of :
- First, Vue uses
initData
parameter passed in by the user
- Then use
new Observer
to observe the - If the data is a
object type, it will call
this.walk(value)
to process the object, and internally usedefineeReactive
define the responsive change of the cyclic object properties. The core is to useObject.defineProperty
to redefine the data.
26-2 Principles of Vue3.x Responsive Data
Vue3.x uses Proxy instead of Object.defineProperty. Because Proxy can directly monitor , and there are as many as 13 interception methods. And as a new standard, it will be subject to continuous performance optimization by browser vendors.
Proxy can only proxy the first layer of the object, so how does Vue3 handle this problem?
Determine whether the current Reflect.get
the return value is the Object
, if so, then by reactive
the agent method, thus achieving a depth observation.
may trigger multiple get/sets when monitoring arrays, so how to prevent multiple triggers?
We can determine key
is the current the proxy object target their own property, you can also determine
old values and
new values are equal, only to meet one of the above two conditions, will it be possible to perform
trigger
.
27. When using calculated attributes, can the function name and the data in the data source have the same name?
Cannot have the same name because no matter it is a calculated attribute, data or props, it will be mounted on the vm instance, so these three cannot have the same name
28. How to solve the problem of static resource image failure after vue packaging
Find the config/index.js
configuration file, and find assetsPublicPath
build
package object. The default value is /
, just change it to ./
29. How to solve the problem that vue dynamically sets the src of img not to take effect?
Because dynamically added src
is when make a deal with static resources, no
compiled, so to add require.
<img :src="require('../../../assets/images/xxx.png')" />
30. How to optimize when using vue to render large amounts of data? Tell me your thoughts!
Object.freeze
Suitable for some big data
business scenarios. Especially when doing the management backend, there are often some super large data volume of
table
, or a chart containing more than n data. The most obvious feeling of using this kind of large data volume is the card. But in fact, in many cases, the data does not actually need to change responsively. At this time, you can use the Object.freeze method, which can freeze an object at (note that it is not a vue-specific api).
When you pass an ordinary JavaScript object to the data option of a Vue instance, Vue will traverse all the properties of this object and use Object.defineProperty to convert all these properties to getter/setter. They allow Vue to track dependencies. Notify changes when accessed and modified.
After using Object.freeze, not only observer
can be reduced, but also the memory overhead of can be reduced.
How to use:
this.item = Object.freeze(Object.assign({}, this.item))
30. Vue custom instructions
Let's first understand that in vue, there are many built-in instructions.
such as:
- v-bind: Attribute binding, which binds data to the attributes of HTML elements.
- v-html & v-text bind data to the attributes of HTML elements, and have the same effect as innerHTML & innerText
- v-on: bind HTML element events
So, regarding the instructions, we can summarize the following points:
- The instruction is written in the
HTML attribute,
<input v-model='name' type='text' />
- The instructions all start
v-
- The right side of the instruction expression can also be followed by the value v-if = false
Vue custom instruction case 1
For example: we need an instruction to write on a certain HTML form element, and then let it automatically get the focus when it is loaded into the DOM.
// 和自定义过滤器一样,我们这里定义的是全局指令
Vue.directive('focus',{
inserted(el) {
el.focus()
}
})
<div id='app'>
<input type="text">
<input type="text" v-focus placeholder="我有v-focus,所以,我获取了焦点">
</div>
Let me summarize a few points first:
- Use
Vue.directive()
to create a newglobal command, (the command is used on the HTML element attribute)
- Vue.directive('focus')
first parameter focus is the
command name. When the command name is declared, there is no need to add v-
- On the HTML element that uses the instruction,
<input type="text" v-focus placeholder="I have v-focus, so I got the focus"/> We need to add v-.
- Vue.directive ( 'Focus', {})
second parameter is a
object, the object
the inside has
inserted()
function, function hasel
this parameter. - The el parameter represents the
DOM element bound to this instruction, here is the latter
placeholder
withinput
, el is equivalent todocument.getElementById('el.id')
- Can use
$(el)
seamlessly connect to jQuery
instruction life cycle
With instructions we need:
- Add a command
- Define the inserted function in the second parameter of the instruction
- Use this instruction on the element that needs to be focused.
When an instruction is bound to an element, there are actually five life cycle event functions inside the instruction.
bind(){}
when the instructionbound to the HTML
element. Only called once.
inserted()
HTML element bound with the instruction is inserted into the
parent element (here the parent element is
div#app
). But there is no guarantee that the parent element has been inserted into the DOM document.updated()
whenVNode of the component where 060c32d2e000b2 is located is updated.
componentUpdate
the VNode of the component where the 060c32d2e000cc instruction is located and its sub-VNodeall updated.
unbind
: Called when the instruction and element, only called once
Vue instruction's life cycle function
Vue.directive('gqs',{
bind() {
// 当指令绑定到 HTML 元素上时触发.**只调用一次**
console.log('bind triggerd')
},
inserted() {
// 当绑定了指令的这个HTML元素插入到父元素上时触发(在这里父元素是 `div#app`)**.但不保证,父元素已经插入了 DOM 文档.**
console.log('inserted triggerd')
},
updated() {
// 所在组件的`VNode`更新时调用.
console.log('updated triggerd')
},
componentUpdated() {
// 指令所在组件的 VNode 及其子 VNode 全部更新后调用。
console.log('componentUpdated triggerd')
},
unbind() {
// 只调用一次,指令与元素解绑时调用.
console.log('unbind triggerd')
}
})
HTML
<div id='app' v-gqs></div>
结果:
bind triggerd
inserted triggerd
It is found that only the bind and inserted life cycle functions are triggered by default.
So when will the remaining three trigger?
<div id='app' >
<p v-gqs v-if="show">v-if是删除或者新建dom元素,它会触发unbind指令声明周期吗?</p>
<button @click="show=!show">toggle</button>
</div>
When the element bound by the instruction is destroyed, the unbind event of the instruction is triggered.
(Create and display, still trigger bind & inserted)
unbind trigger.gif
<p v-gqs v-show="show2">v-show设置元素的display:block|none,会触发componentUpdated事件</p>
<button @click="show2=!show2">toggle-v-show</button>
- One that removes the element from the DOM triggers unbind().---> Just delete.
- When a display setting element is hidden and displayed, componentUpdated() is triggered ---> block | none is triggered.
31. What is the process of vue instance mounting
32. What is the difference between components and plugins
- Component is the business module used to form your App, and its target is App.vue.
- Plugins are functional modules used to enhance your technology stack, and its target is Vue itself.
33. What are the problems (pits) that may be encountered during the use of vue
34. What happens when a new attribute is dynamically added to the vue data
According to the official document definition:
If you add a new attribute
instance is created, it will not trigger a view update.
Vue not allowed been created
the example
dynamically add new
root level responsive properties (root-level reactive property).
However, it can use the Vue.set(object, key, value)
method to add response attributes to nested objects.
35. How to solve the slow loading speed of the first screen of SPA
- Compressed by Gzip
- Use routing lazy loading
- Use the externals attribute in webpack to separate library files that do not need to be packaged to reduce the size of the project after packaging
- Render with SSR
36. mixin
Multiple instances of refer to the same or similar methods or attributes, etc. These repeated content can be extracted as mixins js, exported, and injected into the vue file that needs to be referenced through the mixins attribute, and current instance of The content is merge
.
A mixin object can contain any component options of . With a life cycle,
mixed with objects than
components
executed first.
//Exposing two mixins objects
export const mixinsTest1 = {
methods: {
hello1() {
console.log("hello1");
}
},
created() {
this.hello1();
},
}
export const mixinsTest2 = {
methods:{
hello2(){
console.log("hello2");
}
},
created() {
this.hello2();
},
}
<template>
<div>
home
</div>
</template>
<script>
import {mixinsTest1,mixinsTest2} from '../util/test.js'
export default {
name: "Home",
data () {
return {
};
},
created(){
console.log("1212");
},
mixins:[mixinsTest2,mixinsTest1] // 先调用哪个mixins对象,就先执行哪个
}
</script>
hello2
hello1
1212
37. What is the core of vue
- data driver focuses on the View layer. It allows developers to save the process of manipulating the DOM and only need to change the data.
- component response principle data (model) change drives the view (view) to update automatically
- componentization extends HTML elements to encapsulate reusable code.
38. What are the commonly used modifiers in vue
- v-model: .trim .number
v-on: .stop .prevent
39. Can v-on bind multiple methods?
<input v-model="msg" type="text" v-on="{input:a, focus:b}"/>
40. Understanding of template compilation
41. What is axios and how to interrupt the request of axios
42. How to introduce scss?
Install scss dependent packages:
npm install sass-loader --save-dev npm install node-sass --save-dev
Modify the webpack.base.conf.js file in the build folder, and add the configuration in the rules under the module, as follows:
{ test: /\.scss$/, loaders: ['style', 'css', 'sass'] }
application:
在vue文件中应用scss时,需要在style样式标签上添加lang="scss",即<style lang="scss">。
43. Which of watch and created is executed first in vue
The immediate in watch will make the monitor perform the monitoring calculation when the initial value is declared, otherwise it will be executed first when created
44. What is the difference between created and activated in vue
created() : It is called immediately after the instance is created. In this step, the instance has completed the following configurations: data observer, calculation of properties and methods, and watch/event event callbacks. However, the mount phase has not yet started, and $el property is not yet available.
activated() : This life cycle will only <keep-alive></keep-alive>
when the route is set to 060c32d2e0068a. Called when the component cached by keep-alive is activated.
45. Why is it not recommended to use random numbers or indexes for keys in v-for?
Because when inserting data or deleting data, it will cause the index of the key binding of the following data to change, which will lead to the re-rendering and the efficiency will be reduced
46. How to introduce components in batches
How to use dynamic components
<keep-alive>
<component :is="isWhich"></component>
</keep-alive>
使用标签保存状态,即切换组件再次回来依然是原来的样子,页面不会刷新,若不需要可以去掉。
通过事件改变is绑定的isWhich值即可切换成不同的组件,isWhich的值为组件名称。
47. How to reset data in vue
scenes to be used:
For example, there is a form. After the form is submitted successfully, it is hoped that the component will be restored to the initial state and the data data will be reset.
Use Object.assign()
, vm.$data
to get the data in the current state, and vm.$options.data
to get the data in the initial state of the component
Set the default value of data in the initial state, directly bject.assign(this.$data, this.$options.data())
Description:
- this.$data gets the data in the current state
- this.$options.data() gets the data in the initial state of the component (that is, the initial default value)
- If you only want to modify a certain attribute value of data, you can
this[attribute name] = this.$options.data()[attribute name], such as
this.message = this.$options.data().message
48. How to keep the HTML comments in the template when vue renders the template?
<template comments>
...
</template>
49. The purpose and principle of style plus scoped attribute
- Purpose : Prevent global CSS pollution with the same name
- principle : add
v-data-something
attribute to the label, and then add the corresponding[v-data-something]
, which is the CSS attribute selector, so as to complete the selection method similar to the scope
50. How to configure favicon in the vue project
- Put the favicon picture in the static folder
Then add in index.html:
<link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico">
51. babel-polyfill module
Babel
only converts new JavaScript syntax by default, and does not convert
new APIs, such as global objects
Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise
global objects (such as
Object.assign
).
For example, ES6 added the Array.from method to the Array object. Babel will not transcode this method. If you want this method to
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。