Summary of Vue interview questions

1. Interviewer: Briefly describe MVVM?

MVVM means Model-View-ViewModel, which is to evolve the Controller in MVC into ViewModel. The Model layer represents the data model, the View represents the UI components, and the ViewModel is the bridge between the View and Model layers. The data will be bound to the viewModel layer and automatically render the data to the page. When the view changes, the viewModel layer will be notified to update the data. In the past, the view was updated by manipulating the DOM structure, but now it is a data-driven view.

Advantages of MVVM:

1. Low coupling. The View (View) can be changed and modified independently of the Model. A Model can be bound to different Views. When the View changes, the Model can remain unchanged, and when the Model changes, the View can also remain unchanged;

2. Reusability. You can put some view logic in a Model and let many Views reuse this view logic.

3. Independent development. Developers can focus on business logic and data development (ViewModel), and designers can focus on page design.

4. Testable.

2. Interviewer: Please describe your understanding of the vue life cycle? What is the difference between requesting data in the created and mounted life cycles?

Each Vue instance will go through a series of initialization processes when it is created. Vue's life cycle hook is a function that is triggered when a certain stage or condition is reached. The purpose is to complete some actions or events.

The Vue life cycle can be divided into 8 stages in total: before and after creation, before and after loading, before and after update, before and after destruction, and the life cycle of some special scenarios

life cycle

describe

beforeCreate

When the component instance is created, the data in data and methods has not been initialized and cannot be accessed by vm

created

The component instance has been fully created, there is a value in data, it is not mounted, and can be accessed by vm

beforeMount

Before the component is mounted, the page presents a DOM structure that has not been compiled by Vue, and data can be fetched

Mounted

After the component is mounted on the instance, the DOM can be manipulated at this time, and the page presents the DOM structure compiled by Vue

beforeUpdate

The component data changes, before the update, the data is new but the page is old.

updated

After the component data is updated, the page and data are kept in sync

beforeDestroy

Before the component instance is destroyed, some methods can be manually destroyed at this time

destroyed

After the component instance is destroyed

activated

When the keep-alive cached component is activated

deactivated

Called when keep-alive cached components are deactivated

errorCaptured

Called when an error from a descendant component is caught

Digression: The difference between data requests in created and mouted

created is called immediately after the component instance is created, and the page dom node is not generated at this time; mounted is executed immediately after the page dom node is rendered. Created is earlier than mounted in terms of trigger timing. The same point between the two is that they can get the properties and methods of the instance object. The essence of discussing this issue is the timing of the trigger. The request placed in mounted may cause the page to flash (because the page dom structure has been generated at this time), but if the request is completed before the page is loaded, this will not happen. It is recommended that changes to the page content be placed in the created life cycle.

3. Interviewer: Your understanding of SPA single page

Single-page application SPA is a model of web application or website that interacts with users by dynamically rewriting the current page. This method avoids switching between pages to interrupt the user experience . In a single-page application, all necessary code (HTML, JavaScript, and CSS) is retrieved with the load of a single page, or the appropriate resources are dynamically loaded and added to the page as needed (usually in response to user actions) Page at any time Point will not reload, nor transfer control to other pages.

The well-known JS frameworks such as react, vue, and angular all belong to SPA

4. Interviewer: What is the difference between v-show and v-if? What are the usage scenarios?

In vue, v-show and v-if have the same effect, both can control whether the element is displayed on the page

When the expression is true, it will occupy the position of the page. When the expression is false, it will not occupy the position of the page.

the difference:

1. V-show hiding is to add css--display:none to the element, and the dom element is still there. v-if show hide is to add or delete the whole dom element

2. v-if switching has a partial compilation/unloading process, during which the internal event listener and sub-components are properly destroyed and rebuilt; v-show is simply a css-based switching

3. When v-show changes from false to true, the life cycle of the component will not be triggered

When v-if changes from false to true, trigger the beforeCreate, create, beforeMount, mounted hooks of the component, and trigger the beforeDestory and destroy methods of the component when it changes from true to false

Performance consumption: v-if has higher switching consumption; v-show has higher initial rendering consumption;

Usage scenarios of v-show and v-if

If you need to switch very frequently, it is better to use v-show

If the condition rarely changes at runtime, it is better to use v-if

5. Interviewer: The process of Vue instance mounting

1. When calling new Vue, the _init method will be called

Define $set, $get, $delete, $watch and other methods

Define $on, $off, $emit, $off and other events

Define _update, $forceUpdate, $destroy life cycle

2. Call $mount to mount the page

3. When mounting, it is mainly through the mountComponent method

4. Define updateComponent update function

5. Execute render to generate virtual DOM

6. update generates the real DOM structure from the virtual DOM and renders it into the page

6. Interviewer: What is the priority of v-if and v-for?

The v-if directive is used to conditionally render a piece of content. This content will only be rendered if the directive's expression returns true.

The v-for directive renders a list based on an array. The v-for directive requires a special syntax of the form item in items, where items is the source data array or object, and item is the alias of the array element being iterated

When using v-for, it is recommended to set the key value and ensure that each key value is unique, which facilitates the optimization of the diff algorithm.

1. When v-for and v-if are in the same node, v-for has a higher priority than v-if , which means that v-if will run repeatedly in each v-for loop. If the array to be traversed is very large, but the actual data to be displayed is very small, this will cause a lot of performance waste (Vue2.x)

2. It is recommended to use computed in this scenario, and filter the data first

7. Interviewer: Why is the data in the component a function?

1. If a component is reused multiple times, multiple instances will be created. Essentially, these instances all use the same constructor.

2. If data is an object, the object is a reference type, which will affect all instances and cause data pollution. So in order to ensure that data does not conflict between different instances of components, data must be a function.

8. Interviewer: What happens when a new attribute is dynamically added to Vue's data? How to solve it?

Although the attribute data is directly added, the page is not updated

Because vue2 uses Object.defineProperty to implement data responsiveness, setters and getters can be triggered when we access or set data, but when we add new properties to obj, we cannot trigger the interception of event properties

The reason is that the old properties of obj were set as responsive data at the beginning, but the newly added properties were not set as responsive data through Object.defineProperty

solution:

If you want to update data and views synchronously, you can adopt the following three solutions:

Vue.set()     //Vue.set( target, propertyName, value )
Object.assign()  //创建一个新的对象,合并原对象和混入对象的属性
$forcecUpdated()   //在Vue中做一次强制更新

9. Interviewer: What is the difference between components and plugins in Vue?

A component is a pattern that abstracts various logics of graphics and non-graphics into a unified concept (component) to realize development. In Vue, each .vue file can be regarded as a component

Plugins are often used to add global functionality to Vue

The difference between the two is mainly manifested in the following aspects:

1. Writing form 2. Registration form 3. Usage scenarios

Writing form : The writing form of the component is the Vue single-file form of <template><script><style>

The implementation of the vue plugin should expose an install method. The first parameter of this method is the Vue constructor, and the second parameter is an optional options object

Registration form: Vue component registration is mainly divided into global registration and local registration, and plug-in registration is registered through Vue.use()

scenes to be used

Component is the business module used to make up your App, and its target is App.vue

Plugin (Plugin) is a functional module used to enhance your technology stack, and its goal is Vue itself

Simply put, a plugin is an enhancement or supplement to Vue's functionality

10. Interviewer: What is two-way data binding

One-way binding: Bind the Model to the View. When we update the Model with JavaScript code, the View will be updated automatically. Therefore, we do not need to perform additional DOM operations, and only need to perform Model operations to realize the linkage update of the view. (v-bind form)

Two-way binding: Binding the Model to the View also binds the View to the Model, so that the automatic update of the View can be realized by updating the Model, and the update of the Model data can also be realized by updating the View. Therefore, when we update the Model with JavaScript code, the View will be updated automatically. Conversely, if the user updates the View, the data of the Model will be updated automatically. (v-model form)

Mainly rely on ViewModel's listener and parser to realize two-way data binding

11. Interviewer: What are the communication methods between Vue components?

Eight general communication schemes in vue:

1. Pass through props (parent component to child component)

The parent component passes the value through the literal value in the child component tag, such as <son:msg="msgData" ></son>

The subcomponent sets the props attribute to define the parameters passed by the parent component. Such as props: ["msg"]

2. Trigger a custom event through $emit (the child component is passed to the parent component)

The subcomponent triggers a custom event through $emit, and the second parameter of $emit is the passed value

this.$emit('add',good) // Trigger the method of the parent component and pass the parameter good

The parent component binds the listener to get the parameters passed by the child component

<Children@add="cartAdd($event)" />

3. Use ref (child component to parent component)

The parent component sets ref when using the child component

The parent component gets data by setting the child component ref

<Childrenref="foo" />

this.$refs.foo // Get the subcomponent instance, we can get the corresponding data through the subcomponent instance

4. Global event bus (parent-child components, non-parent-child components)

The eventBus event bus is suitable for communication between parent-child components, non-parent-child components, etc.

Create a global event bus EventBus

The sending component triggers a custom event through $emit, and the second parameter of $emit is the passed value

The receiving component listens to custom events through $on

5. Dependency injection (provide/inject) (parent-child components, grandparents and grandchildren components)

Define the provide attribute in the ancestor component and return the passed value

In the descendant component, receive the value passed by the component through inject

6, vuex

Vuex implements a one-way data flow, and has a State to store data globally. When a component wants to change the data in the State, it must be done through Mutation. Mutation also provides a subscriber mode for external plug-ins to call to obtain State data updates. However, when all asynchronous operations (commonly used to call the back-end interface to obtain update data asynchronously) or batch synchronous operations require actions, actions cannot directly modify the state, and mutations are still required to modify the state data. Finally, according to the change of State, it is rendered to the view.

7、$parent/ $children

Use $parent to let the component access the instance of the parent component

Use $children to allow components to access instances of child components

8、$attrs/ $listeners

Applicable scenario: ancestors pass data to descendants

Set batch download attributes $attrs and $listeners

Contains property bindings that are not recognized (and fetched) as props in the parent scope

Internal components can be passed in via v-bind="$attrs"

12. Interviewer: What is the function of $nextTick in Vue?

Vue's dom update is asynchronous. It does not change the dom immediately after the data changes, but after all the data changes in the same event loop are completed, the view is updated uniformly.

Scenarios used by $nextTick():

The dom in the created stage is not generated for rendering. If we want to get the dom in this life cycle at this time, we can use the nextTick method to get it

In the mounted phase, if you need to manipulate the rendered view, use the nextTick method, because the mounted hook does not promise that its subcomponents are also mounted

$nextTick() principle and its use

Delays the execution of the callback until after the next DOM update cycle. Use it immediately after modifying the data, then wait for the DOM to update. It is the same as the global method Vue.nextTick, the difference is that the this of the callback is automatically bound to the instance that called it.

13. Interviewer: Tell me about your understanding of Vue's mixin. What are the application scenarios?

mixin (mixing in), provides a very flexible way to distribute reusable functions in Vue components.

The essence is actually a js object, which can contain any functional options in our components, such as data, components, methods, created, computed, etc.

We only need to pass the shared function into the mixins option in the form of an object. When the component uses the mixins object, all the options of the mixins object will be mixed into the options of the component itself.

In Vue we can mix in locally and globally

14. Interviewer: Tell me about your understanding of slot? What are the usage scenarios of slots?

The slot in vue is a very useful thing. A slot is simply a placeholder. There are three types of slots in vue, one is the default slot (anonymous), the other is a named slot, and the other is One is scoped slots, anonymous slots have no name, as long as the default ones are filled here, named slots refer to those with names, and the difference between scoped slots is that when subcomponents render scoped slots, You can pass the data inside the child component to the parent component, and let the parent component decide how to render the slot based on the data passed from the child component.

The child component uses the <slot> tag to determine where to render, and the parent component uses

Through slots, users can extend components to better reuse and customize components

15. Interviewer: Have you ever understood Vue.observable? Tell me

Observable translates and we can understand it as observable

Definition in Vue:

Vue.observable, making an object into responsive data. Vue will use it internally to process the object returned by the data function

The returned object can be used directly in render functions and computed properties, and will trigger corresponding updates when changes occur. Can also be used as a minimal cross-component state store

In Vue 2.x, the passed object will be directly changed by Vue.observable, which is the same object as the returned object

scenes to be used

When non-parent-child components communicate, you can use the usual bus or use vuex, but the implemented functions are not too complicated, and using the above two is a bit cumbersome. At this time, observable is a good choice

16. Interviewer: Do you know the principle of key in Vue? talk about your understanding of it

The function of the key is to find the corresponding node faster when the diff algorithm is executed, improve the diff speed, and update the virtual DOM more efficiently;

Both vue and react use the diff algorithm to compare the old and new virtual nodes to update the nodes. In Vue's diff function, the key in the old node array will be compared with the key of the new node to find the corresponding old node. If not found, it is considered a new node. And if there is no key, then the corresponding old node will be found by traversal search. One is a map mapping, and the other is a traversal search. in comparison. Map mapping is faster.

17. Interviewer: Tell me what is your understanding of keep-alive?

keep-alive is a built-in component in vue, which can keep the state in memory during component switching to prevent repeated rendering of DOM. When wrapping dynamic components with keep-alive, inactive component instances are cached instead of being destroyed

<keep-alive>
  <component ></component>
</keep-alive>

Scenario: We can use keepalive when we don't need to reload the page in some scenarios

Such as tabs tab page background navigation, vue performance optimization

Principle: Vue.js internally abstracts DOM nodes into individual VNode nodes, and the cache of keep-alive components is also based on VNode nodes instead of directly storing DOM structures. It will cache the components that meet the conditions (pruneCache and pruneCache) in the cache object, and then take the vnode node out of the cache object and render it when it needs to be re-rendered.

18. Interviewer: What are the commonly used modifiers for Vue? What are the application scenarios

Modifiers in Vue are divided into the following five types:

1. Form modifier 2, event modifier 3, mouse button modifier 4, key value modifier 5, v-bind modifier

1. Form modifiers

lazy: When we fill in the information and the cursor leaves the label, the value will be assigned to value (v-model.lazy)

trim: automatically filter the first space character entered by the user, and the space in the middle will not be filtered (v-model.trim)

number: Automatically convert the user's input value to a numeric type (v-model.number)

2. Event modifiers

stop: prevents the event from bubbling, which is equivalent to calling the event.stopPropagation method (@click.stop)

prevent: Prevent the default behavior of the event, which is equivalent to calling the event.preventDefault method (@.prevent)

self: Only trigger the handler when event.target is the current element itself (@click.self)

once: After the event is bound, it can only be triggered once, and it will not be triggered the second time (@click.once)

capture: Make the event trigger trigger down from the top level containing this element

passive: On the mobile side, when we are listening to element scrolling events, the onscroll event will always be triggered and our web page will become stuck, so when we use this modifier, it is equivalent to adding a .lazy modifier to the onscroll event

Native: Let the component listen to the native event of the root element like a built-in HTML tag, otherwise v-on on the component will only listen to custom events

3. Mouse Button Modifiers

left left click right right click middle middle click example (@click.left)

4. Keyboard Modifiers

Keyboard modifiers are used to modify keyboard events (onkeyup, onkeydown) (@keyup.keyCode)

Five, v-bind modifier

The v-bind modifier is mainly used to operate on attributes, abbreviated as a colon

19. Interviewer: Have you ever written a custom instruction? What are the application scenarios of custom commands?

In addition to the default built-in instructions (v-model and v-show) of the core functions, Vue also allows the registration of custom instructions. Global registration is mainly through the Vue.directive method. The first parameter of Vue.directive is the name of the instruction (not Need to write v-prefix), the second parameter can be object data, or an instruction function

Partial registration by setting the directive attribute in the component options option

//注册一个全局自定义指令 `v-focus`
Vue.directive('focus',{
  // 当被绑定的元素插入到DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus() // 页面加载完成之后自动让输入框获取到焦点的小功能
  }
})
directives:{          //局部注册
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus() // 页面加载完成之后自动让输入框获取到焦点的小功能
    }
  }
}

Then you can use the new v-focus on any element in the template

Application Scenario

1. Prevent repeated submission of forms 2. Lazy loading of pictures 3. One-click copy function

20. Interviewer: Do you understand the filters in Vue? What are the application scenarios of filters?

The filter does not change the original data in essence, but only processes the data and returns the filtered data before calling and processing. We can also understand it as a pure function

Filters in vue can be used in two places: double curly braces interpolation and v-bind expressions, filters should be added at the end of JavaScript expressions, indicated by the "pipe" symbol

Define local filters in component options

filters:{
  capitalize: function (value) {
    if (!value) return ''
    value = value.toString()
    return value.charAt(0).toUpperCase() +value.slice(1)
  }
}
过滤器可以串联:
{
    
    {message | filterA | filterB }}

Define a global filter:

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
  // ...
})

Application Scenario

In normal development, there are many places that need to use filters, such as unit conversion, number management, text formatting, time formatting, etc.

21. Interviewer: What is virtual DOM? How to implement a virtual DOM? tell me your thoughts

What is virtual DOM

In fact, it is just a layer of abstraction to the real DOM. The tree is based on JavaScript objects (VNode nodes), and the properties of the objects are used to describe the nodes. Finally, the tree can be mapped to the real environment through a series of operations

Why do you need a virtual DOM

The cost of operating the DOM is still expensive, and frequent operations will still cause page freezes, which will affect the user experience

And through VNode, also update 10 DOM nodes, the virtual DOM will not operate the DOM immediately, but save the diff content of these 10 updates to a local js object, and finally attach this js object to the DOM tree at one time , to avoid a large number of unnecessary calculations

The biggest advantage of virtual DOM is that it abstracts the original rendering process and realizes cross-platform capabilities. It is not limited to the browser's DOM. It can be the native component of Android and IOS, it can be a very popular small program recently, or it can be is a variety of GUI

How to implement a virtual DOM

createElement is the process of creating VNode, each VNode has children, and each element of children is also a VNode, thus forming a virtual tree structure to describe the real DOM tree structure

22. Interviewer: Do you know the diff algorithm of Vue? Tell me

When does the diff algorithm run? Run the update function when the value that our current component depends on is updated and the component is created. The update function will call the render function of the component, and render will generate a new virtual dom tree. Update will replace the old virtual dom tree with a new virtual dom tree, and then use A variable saves the old virtual dom tree, and then calls the patch function for diff comparison

Then Vue's diff will perform a depth-first comparison of the same layer according to the new and old domTree. If the parent node is compared and found to be different, all child nodes of the parent node do not need to be compared and die together with the parent node. If the parent node is compared and found to be the same, continue to go Next compare the child nodes of the parent node and then compare the child nodes of the next parent node, so as to recursively compare. When comparing, first compare whether the tag names are consistent, and then compare whether the key values ​​of the elements are the same. If it is input The elements will also compare the type types. If they are all the same, they are the same. If they are different, they are not the same . Vue's diff algorithm will record the head and tail pointer positions at the head and tail of the old and new DOM trees, gather them together, and gradually compare them to ensure High reuse of real dom, when the head pointer of the new virtual dom tree is greater than the tail pointer of the new virtual dom tree, it means that the comparison of the new virtual dom tree is completed, the diff is over, and then vue will be based on the truth of the comparison result of the new virtual dom tree The dom tree is added to the root node to complete the rendering of the real dom of the page

23. Interviewer: Has axios been packaged in the Vue project? What is the main package?

Axios has been encapsulated. Every time axios initiates an HTTP request, it needs to write these operations such as setting the timeout period, setting the request header, judging which request address to use according to the project environment, error handling, and so on. This kind of duplication of work not only wastes time, but also makes the code redundant and difficult to maintain. In order to improve our code quality, we should encapsulate axios twice in the project before using

Packaging aspects:

1. Set the interface request prefix: use the node environment variable to make a judgment, which is used to distinguish the development, test, and production environments

2. Set the request header and timeout

3. Encapsulate the request method: first introduce the encapsulated method, re-encapsulate the interface to be called into a method and expose it, and put the encapsulated method in an api.js file

4. Request interceptor: request interceptor can add token to each request, and it is easy to maintain after unified processing

5. Response interceptor: After receiving the response, one layer of operations can be performed first, such as judging the login status and authorization according to the status code

24. Interviewer: Do you understand the principle of axios?

Implement a simple version of axios, then export the axios instance, and get the final global variable axios

classAxios {
    constructor() {
 
    }
    request(config) {
        return new Promise(resolve => {
            const {url = '', method = 'get',data = {}} = config;
            // 发送ajax请求
            const xhr = new XMLHttpRequest();
            xhr.open(method, url, true);
            xhr.onload = function() {
                console.log(xhr.responseText)
                resolve(xhr.responseText);
            }
            xhr.send(data);
        })
    }
}
//最终导出axios的方法,即实例的request方法
functionCreateAxiosFn() {
    let axios = new Axios();
    let req = axios.request.bind(axios);
    return req;
}
 
//得到最后的全局变量axios
letaxios = CreateAxiosFn();

25. Interviewer: What problem does SSR solve?

Server-SideRendering We call it SSR, which means server-side rendering

Refers to the page processing technology that completes the splicing of the HTML structure of the page by the server side, sends it to the browser, and then binds the status and events to it to become a fully interactive page.

Traditional web development: web page content is rendered on the server side and transmitted to the browser at one time

Single-page application SPA: The excellent user experience of single-page applications makes it gradually become the mainstream. The page content is rendered by JS. This method is called client-side rendering.

SSR solution, the backend renders the complete first screen dom structure and returns it, the content obtained by the front end includes the first screen and the complete spa structure, after the application is activated, it still runs in the spa mode

SSR mainly solves the following two problems:

1. Conducive to seo

2. Rendering of the first screen: users can see the page view without waiting for all js to be loaded on the page (the pressure comes to the server, so it is necessary to weigh which ones are rendered by the server and which ones are handed over to the client)

26. Interviewer: Tell me about the directory structure of your Vue project. If it is a large-scale project, how should you divide the structure and components?

Using Vue to build projects, a clear project structure will improve development efficiency, and familiarity with various configurations of the project will also make development efficiency higher. When dividing the project structure, some basic principles need to be followed:

1. Semantic consistency of folders and files inside folders

Such as the pages folder, this folder should contain all the routing modules of our project, and should only contain routing modules, and there should be no other non-routing module folders

2. Single entry/exit

No matter how messy your module folder is inside, when it is referenced externally, it is imported from an entry file

3. The principle of proximity, tightly coupled files should be put together and referenced with relative paths

4. Public files should be referenced from the root directory with an absolute path

5. Files outside /src should not be imported

Directory Structure:

build folder, used to store project build scripts

Some basic configuration information of the project is stored in config, the most commonly used is port forwarding

The node_modules directory stores all dependencies of the project, that is, the files downloaded by the npm install command

The source code of the project is stored in the src directory, that is, the code written by the developer is placed here

static is used to store static resources

index.html is the home page of the project, the entry page, and the only HTML page of the entire project

All dependencies of the project are defined in package.json, including development-time dependencies and release-time dependencies

The file directory in src is as follows :

The assets directory is used to store asset files

The components directory is used to store components (some reusable, non-independent pages). Of course, developers can also directly create complete pages in components.

It is recommended to store components in components, and create a separate page folder for routing pages.

In the router directory, the js file of the route is stored

App.vue is a Vue component and the first Vue component of the project

main.js is the entry js of the whole project

27. Interviewer: What should vue do to manage permissions? What if the permissions are controlled to the button level?

In the final analysis, the front-end authority is the right to initiate the request, and the initiation of the request may be triggered by the following two forms

1. Triggered by page loading 2. Triggered by button click on the page

1. Interface permissions

After logging in, get the token, save the token, and intercept it through the axios request interceptor. Every time a request is made, the header carries the token

2. Routing authority control

When initializing, first mount routes that do not require permission control, such as login pages, 404 and other error pages. If the user performs mandatory access through the URL, it will directly enter 404, which is equivalent to controlling from the source. After logging in, obtain the user's permission information, then filter the routes that have permission to access, and call addRoutes in the global route guard to add routes

3. Button permissions

Button permissions can also be judged by v-if, or button permissions can be judged through custom instructions

4. Menu Permissions

1. The menu is separated from the routing, and the menu is returned by the backend

2. The menu and routing are returned by the backend

28. Interviewer: How do you solve cross-domain in the Vue project?

The essence of cross-domain is a security method for browsers based on the same-origin policy

The same-origin policy means that the port numbers of the protocol hosts are all the same to access

On the contrary, non-same-source requests, that is, when one of the protocols, ports, and hosts are different, cross-domain requests will occur at this time

There are many ways to solve cross-domain JSONP, CORS, Proxy

In the vue project, it is mainly developed for the two schemes of CORS or Proxy

1. As long as the backend implements CORS, cross-domain is realized, and only some HTTP headers need to be added to allow the server to declare the allowed access sources

2. Proxy proxy server

We can set up a local server as the proxy object of the request through webpack, forward the request to the target server through the server, get the result and forward it to the front end

proxy:{
      '/api': { // '/api'是代理标识,用于告诉node,url前面是/api的就是使用代理的
      target:"http://xxx.xxx.xx.xx:8080", //目标地址,一般是指后台服务器地址
      changeOrigin: true, //是否跨域
      pathRewrite: {         // pathRewrite 的作用是把实际Request Url中的'/api'用""代替
           '^/api': "" 
      }

29. Interviewer: What is the reason for reporting 404 after the local development of the Vue project is completed and deployed to the server?

The routine front-end deployment only needs to upload a series of static files generated after the Vue project is built to the target server

HTTP404 error means that the resource pointed to by the link does not exist, this problem only occurs in history mode

When performing a refresh operation, there is no relevant configuration in history mode, so 404 will appear

But there is no problem in hash mode because although the hash appears in the URL, it will not be included in the HTTP request and has no effect on the server, so changing the hash will not reload the page

solution:

The core of the problem is that when we refresh the page when we enter the sub-routing, 404 will appear when there is no corresponding page in the web container, so we only need to configure to redirect any page to index.html, and hand over the routing to the front-end for processing can

30. Interviewer: How do you deal with errors in the Vue project?

Major sources of errors include:

1. Backend interface error 2. Logic error in the code itself

Back-end interface errors can be implemented through the interceptor of axios to implement a layer of interception first for the response of the network request

code logic problem

  1. Set a global error handler

Vue.config.errorHandler= function (err, vm, info) {
}

errorHandler specifies the handler for uncaught errors during rendering and viewing of the component. When this handler is called, the error message and Vue instance can be obtained

2. Life cycle hooks

errorCaptured is a new life hook function that is called when an error from a descendant component is captured

31. What are the commonly used commands for Vue? and explain its role

1.v-model

Role: It is mostly used for form elements to realize two-way data binding

2.v-bind dynamic binding

Dynamically bind values ​​for attributes of elements, generally abbreviated as:

Function: Change the data of the page in time

3. v-for dynamic rendering

The v-for directive renders a list based on an array. It is recommended to set the key value and ensure that each key value is unique, which facilitates the optimization of the diff algorithm

4. v-show display content

The principle of v-show is to dynamically add or remove `display` styles for elements to display and hide elements

5. v-if display and hide

The principle of v-if is to dynamically create or remove elements on the DOM tree to realize the display and hiding of elements

6. v-on binds functions to tags

It can be abbreviated as @, for example, binding a click function must be written in methods

7. v-text and v-html parse text

v-text: Used to parse text, but not tags, and will overwrite the original content inside the element!

v-html: It can render tagged strings into real HTML content!

32. Understanding and usage scenarios of Vuex

Vuex is a state management pattern developed specifically for Vue applications. At the heart of every Vuex application is the store

Vuex's state store is responsive; when a Vue component reads state from the store:

1. If the state in the store changes, the corresponding components will be efficiently updated accordingly

2. The only way to change the state in the store is to explicitly submit the mutation, which allows us to easily track each state change. Vuex mainly includes the following core modules:

3. State: defines the state data of the application

4. Getter: Define "getter" in the store (which can be considered as the calculated property of the store),

Just like computed properties, the return value of a getter is cached according to its dependencies, and will only be recomputed when its dependent values ​​change

5. Mutation: It is the only way to change the state in the store, and it must be a synchronous function

6. Action: used to submit mutations instead of directly changing the state, and can contain any asynchronous operations

7. Module: Allows a single Store to be split into multiple stores and stored in a single state tree at the same time

Guess you like

Origin blog.csdn.net/weixin_55608297/article/details/129626400