Home >Web Front-end >JS Tutorial >Nine common vuejs interview questions, do you know them?
11 common vuejs interview questions, do you know them? From vue interview questions column
MVVM is the abbreviation of Model-View-ViewModel
Model represents the data model, and business logic for data modification and operation can also be defined in the Model.
View represents the UI component, which is responsible for converting the data model into UI display.
ViewModel monitors changes in model data, controls view behavior, and handles user interaction. A simple understanding is an object that synchronizes View and Model and connects Model and View.
Under the MVVM architecture, there is no direct connection between View and Model. Instead, they interact through ViewModel. The interaction between Model and ViewModel is two-way, so changes in View data will be synchronized to the Model, and the Model Changes in data will also be immediately reflected on the View.
ViewModel connects the View layer and the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need to focus on business logic and do not need manual operations. DOM does not need to pay attention to the synchronization of data status. Complex data status maintenance is completely managed by MVVM.
Before the data observation and initialization events have started
Complete data observation, operation of properties and methods, initialization events, el attribute has not yet been displayed
is called before the mounting starts, The relevant render function is called for the first time. The instance has completed the following configuration: compile the template, and generate html from the data in the data and the template. Note that the html has not been mounted on the page at this time.
Called after el is replaced by the newly created vm.$el and mounted to the instance. The instance has completed the following configuration: replace the DOM object pointed to by the el attribute with the compiled html content above. Complete the rendering of the html in the template into the html page. Ajax interaction is performed during this process.
Called before the data is updated, which occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering an additional re-rendering process.
Called after virtual DOM re-rendering and patching due to data changes. When called, the component DOM has been updated, so DOM-dependent operations can be performed. In most cases, however, changing state during this period should be avoided, as this may cause an infinite loop of updates. This hook is not called during server-side rendering.
Called before the instance is destroyed. The instance is still fully available.
Called after the instance is destroyed. After calling, all event listeners will be removed and all child instances will be destroyed. This hook is not called during server-side rendering.
Answer: The process from creation to destruction of a Vue instance is the life cycle. A series of processes from starting to create, initializing data, compiling templates, mounting Dom→rendering, updating→rendering, and destruction are called the life cycle of Vue.
Answer: There are multiple event hooks in its life cycle, making it easier for us to form good logic when controlling the process of the entire Vue instance.
Answer: It can be divided into 8 stages in total: before/after creation, before/after loading, before/after update, before/after destruction.
Answer: The following beforeCreate, created, beforeMount, mounted will be triggered.
Answer: DOM rendering is completed in mounted.
Vue implements two-way data binding mainly by using data hijacking combined with the publisher-subscriber model. Use Object.defineProperty() to hijack the setters and getters of each property, publish messages to subscribers when the data changes, and trigger corresponding listening callbacks. When you pass a plain Javascript object to a Vue instance as its data option, Vue will iterate through its properties and convert them into getters/setters using Object.defineProperty. The getters/setters are not visible to the user, but internally they allow Vue to track dependencies and notify changes when properties are accessed and modified.
Vue's two-way data binding uses MVVM as the entrance to data binding, integrating Observer, Compile and Watcher. It uses Observer to monitor the data changes of its own model, and uses Compile to parse and compile template instructions (vue is used to parse {{}}), and finally uses watcher to build a communication bridge between observer and Compile to achieve data change -> view update; view interactive change (input) -> data model change two-way binding effect .
<p> <input> </p><p></p> <script> var obj = {} Object.defineProperty(obj, 'txt', { get: function () { return obj }, set: function (newValue) { document.getElementById('txt').value = newValue document.getElementById('show').innerHTML = newValue } }) document.addEventListener('keyup', function (e) { obj.txt = e.target.value }) </script>
1. Value transfer between parent component and sub-component
Parent component passes to sub-component: sub-component receives data through props method;
Sub-component Passed to the parent component: $emit method passes parameters
2. Data transfer between non-parent and child components, sibling components pass values
eventBus is to create an event center, equivalent to a transfer station, which can be used to transfer events and Receive events. If the project is relatively small, this is more appropriate. (Although many people recommend using VUEX directly, it depends on the needs. Technology is just a means, and achieving the goal is the king.)
In the browser, the symbol "#", # and the characters after # are called hash, and are read with window.location.hash;
Features: Although hash is in the URL , but not included in the HTTP request; used to guide browser actions, useless for server-side security, and the hash will not reload the page.
In hash mode, only the content before the hash symbol will be included in the request, such as http://www.xxx.com. Therefore, for the backend, even if full coverage of routing is not achieved, A 404 error will be returned.
history adopts the new features of HTML5; and provides two new methods: pushState(), replaceState() to modify the browser history stack, and the popState event to monitor status changes.
In history mode, the URL of the front end must be consistent with the URL that actually initiates the request to the back end, such as http://www.xxx.com/items/id. If the backend lacks routing processing for /items/id, a 404 error will be returned. The Vue-Router official website describes this: "However, to play well in this mode, it also requires background configuration support... Therefore, you need to add a candidate resource on the server side that covers all situations: if the URL does not match any static resources, Then the same index.html page should be returned, which is the page your app depends on."
The status that is only used to read is concentrated in the store Medium; The way to change the state is to submit mutations, which is a synchronous thing; asynchronous logic should be encapsulated in actions.
Introduce store into main.js and inject it. A new directory store is created,...export.
Scenarios include: In a single-page application, the state between components, music playback, login status, and adding to the shopping cart
Vuex uses a single state tree, that is, each application will Contains only one store instance, but a single state tree does not conflict with modularity. The stored data status cannot be modified directly.
The methods defined by mutations dynamically modify the state or data in the Vuex store.
Computed properties similar to vue are mainly used to filter some data.
actions can be understood as changing the method of processing data in mutations into a method that can process data asynchronously. Simply put, it is asynchronous operation of data. The view layer distributes actions through store.dispath.
When the project is particularly complex, each module can have its own state, mutation, action, and getters, making the structure very clear and easy to manage.
//store实例 const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })
var app = new Vue({ el: '#app', data: { }, // 创建指令(可以多个) directives: { // 指令名称 dir1: { inserted(el) { // 指令中第一个参数是当前使用指令的DOM console.log(el); // 对DOM进行操作 el.style.width = '200px'; el.style.height = '200px'; el.style.background = '#000'; } } } })
Vue.directive('dir2', { inserted(el) { console.log(el); } })
<p> </p><p></p> <p></p>
<p> <input> {{msg| capitalize }} </p>
var vm=new Vue({ el:"#app", data:{ msg:'' }, filters: { capitalize: function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } } })
Vue.filter('capitalize', function (value) { if (!value) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) })
Answer: Just write scoped in the style tag. For example:
Answer: v-if renders according to conditions, v-show is display block or none;
Answer: Router is a "routing instance" object that includes routing jump methods, hook functions, etc.
Answer: Data-driven, component system
Answer: v-for, v-if, v-bind, v-on , v-show, v-else
Answer: .prevent: The submit event will no longer reload the page; .stop: Prevent the click event from bubbling; .self: It will be triggered when the event occurs in the element itself rather than in the sub-element; .capture : Event listening,
Answer: Yes
Answer: When Vue.js uses v-for to update the rendered element list, it defaults to the "in-place reuse" strategy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element there and make sure it displays each element that has been rendered at a specific index. The main role of key is to efficiently update the virtual DOM.
Answer: Putting too much logic in the template will make the template overweight and difficult to maintain. When complex processing of data is required and may be used multiple times, try to use calculated attributes. Benefits: ① Makes the data processing structure clear; ② Depends on the data, the data is updated, and the processing results are automatically updated; ③ This inside the calculated attribute points to the vm instance; ④ When the template is called, just write the calculated attribute name directly; ⑤ The commonly used getter method, to obtain data, you can also use the set method to change the data; ⑥ Compared with methods, methods will be recalculated regardless of the dependent data changing, but when the dependent data remains unchanged, computed will be obtained from the cache and will not be recalculated.
Answer: Advantages: The goal of Vue is to achieve responsive data binding and combined view components through the simplest possible API. The core is a reactive data binding system. MVVM, data-driven, componentized, lightweight, concise, efficient, fast, and module-friendly.
Disadvantages: Does not support lower version browsers, only supports IE9 at least; not conducive to SEO optimization (if you want to support SEO, it is recommended to render components through the server); it takes a relatively long time to load the homepage for the first time ;You cannot use the browser's navigation buttons and need to realize forward and backward by yourself.
Answer: In the index.js file in the router directory, add /:id to the path attribute , obtained using the params.id of the router object.
The above is the detailed content of Nine common vuejs interview questions, do you know them?. For more information, please follow other related articles on the PHP Chinese website!