vue organize knowledge

First, for MVVM understanding?

MVVM is a Model-View-ViewModel acronym.
Model representative of the data model, the data can also define and modify business logic operations in the Model.
View  behalf of UI components, which is responsible for the data model into UI unfolded.
ViewModel  change behavioral monitor and control the view of the model data, user interaction processing, synchronization object is a simple to understand and Model View connected and Model View.
In MVVM architecture, between the View and the Model no direct contact, but through the interaction between the interaction ViewModel, Model and ViewModel is bidirectional, so change View data will be synchronized to the Model, the data varies Model also react immediately to the View.
ViewModel  through the two-way data binding layer and the Model-View is connected up, and synchronization between the View and Model entirely automatic, without human intervention, so developers can focus on the business logic, the DOM does not require manual operation, not We need to focus on the state of the data synchronization issues, the state of maintenance of complex data entirely unified management MVVM.

Two, Vue life cycle

beforeCreate (before creation) in the observation data has not yet started and initialization event
created to complete the operation observation data, properties, and methods (after creation), initialization event, $ el property also does not show up
beforeMount (pre-loaded) before beginning to mount is called, the associated render function is called for the first time. Examples completed following configuration: compiling templates, and the template data inside the data generated html. Note that at this time not to mount html page.
Mounted (after loading). $ el replaced vm el newly created, and mount to call up after instance. Examples completed following configuration: The above compiled html replaces el DOM object attribute points. Completed template to render html html page. This process is carried ajax interaction.
beforeUpdate (before update) before data update call, take place in the virtual re-rendering and DOM before patching. Can further change the status of the hook, the weight will not trigger additional rendering process.
Updated (updated) called after the DOM data change caused due to the virtual rendering and re-patching. When you call, DOM component has been updated, so you can rely on to perform DOM operations. However, in most cases, you should avoid changing the state during this period, as this may result in an infinite loop update. The hook is not called during server-side rendering.
beforeDestroy (before the destruction) called before instances destroyed. Examples of still fully available.
Destroyed (later destroyed) called after the instance is destroyed. After the call, all event listeners will be removed, all the child instance will be destroyed. The hook is not called during server-side rendering.
1. What is the life cycle vue?
A: Vue instance process from creation to destruction, is life cycle. From the beginning of creation, initialization data, compiled templates, Mount Dom → rendering, rendering update → destruction and a series of process, called Vue life cycle.

What is the role 2.vue life cycle is?
A: It's the life cycle of multiple events hook, make it easier for us to form good logic in the control of the entire process Vue instance.

3.vue total life cycle stages?
A: It can be divided into a total of eight stages: before creating / rear, before loading / after update before / after the destruction before / after the destruction.

4. The first page load which will trigger a few hooks?
A: The following will trigger these beforeCreate, created, beforeMount, mounted.

5.DOM rendering has been completed in which period?
A: DOM rendering mounted in has been completed.

Three, Vue implement the principle of two-way data binding: Object.defineProperty ()

vue achieve two-way data binding is mainly: mining data combined hijacked Publisher - Subscriber Model manner by Object.defineProperty () to hijack setter of each property, getter, posted a message to subscribers when data changes, trigger the corresponding monitor callback. When the object is passed to a common Javascript Vue instance as its data option, Vue will traverse its properties, they are converted by Object.defineProperty getter / setter. Users do not see getter / setter, but internally they let Vue track dependent, when informed of the changes in the property is accessed and modified.

The two-way data binding vue MVVM data entry as binding, the Observer integration, Watcher Compile and three, to monitor their model data changes by the Observer, compiled template to parse command (vue is used by parsing {Compile {}}), using a watcher finally acts as a bridge between the observer and the Compile, to achieve the data change -> view update; view change interaction (INPUT) -> data model changes way binding effect.

js achieve a simple way binding

<body>
    <div id="app"> <input type="text" id="txt"> <p id="show"></p> </div> </body> <script type="text/javascript"> 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>

Fourth, the parameters passed between components Vue

1. The parent component and subassembly traditional values
parent element subassembly passed: data receiving sub-assembly method props;
subassembly pass parent element: $ EMIT method to pass parameters
2. Data transfer between the non-parent-child assembly, pass component value brothers
eventBus, is to create an event center, equivalent to a transit station, you can use it to transfer events and receive event. The project is small, with the more appropriate. (Although there are many people recommend directly VUEX, specifically to see demand slightly. Technology is only a means to achieve the purpose is king.)

V. routing Vue realization: hash mode and history mode

hash mode: the browser symbol "#", # and # characters behind called hash, reading the window.location.hash;
Features: although the hash in the URL, but not included in the HTTP request; with to guide the browser action for server security useless, hash will not reload the page.
the hash mode, only the hash symbols before content is included in the request, such as  http://www.xxx.com , so the rear end, even if there is no route to achieve full coverage, does not return 404 error.

mode history: history using the new HTML5 features; and provides two new methods: pushState (), replaceState () can modify the browser history stack, and listen popState events to the state change.
the history mode, the front end of the URL and the URL must initiate a request to the rear end of the actual consistency, such as  http://www.xxx.com/items/id . If the lack of rear / items / id route processing, returns a 404 error. Vue-Router official website in such a description: "But this mode to play well, but also the background configuration support ...... So, you want to add a candidate resources to cover all situations in the service side: if the URL match any static resources, you should return the same index.html page, which is dependent on your app page. "

Sixth, the difference between Vue and the Angular and React?

(Version constantly updated, the following differences there may not be quite right in my job used only vue, for angular and react very familiar.)
Difference 1. AngularJS with the
same point:
support instruction: built-in commands and custom instructions ; support the filter: built-in filters and custom filters; supports two-way data binding; do not support low-end browser.

Different points:
High cost AngularJS learning, such as increased Dependency Injection characteristics, and provides API Vue.js themselves are relatively simple and intuitive; in performance, the dependence on the data to make dirty AngularJS examination, the more so the slower Watcher; Vue .js-based tracking relies observation and the use of asynchronous queue update, all data is independent of the trigger.

2. React difference with the
same point:
React with a special JSX grammar, Vue.js component development is also respected in the preparation of .vue special file format, the file contents have some agreement, after both need to compile using; the central idea the same: everything components can be nested between component instance; provide reasonable hook function that allows developers to customize the processing requirements; not built columns AJAX, Route and other functions to the core package, but in way plug-in is loaded; support mixins characteristics of the component development.
Different points:
the Virtual will render the DOM using React results do dirty examination; Vue.js provides instructions, filters, etc. in the template can be very easily and quickly operated Virtual DOM.

Seven, vue routing hook function

Home can control the navigation jump, beforeEach, afterEach, are generally used to modify the title of the page. Some need to be logged in to adjust the redirection page.

beforeEach There are three parameters to, from, next:

to : the target is about to enter the route object route,

from : the route was about to leave the current navigation route

the Next : function must call the method resolve this hook. Implementation of the results depend on the method call parameters next. You can control the jump pages.

Eight, what vuex that? how to use? Which Scenario to use it?

Reads only in a state focused on the store; change of state is the way to submit mutations, which is sync thing; asynchronous logic should be encapsulated in the action.
Store introduced in main.js, injection. Create a directory store, ... .. export.
Scene: single-page application, the state between components, music player, logged, Add to Cart
image description

State
Vuex single state tree, i.e., each application will contain only a store example, but a single state does not conflict tree and modular. Stored data state, which can not directly modify the data.
mutations
method defined mutations store Vuex dynamic modification of the state or data.
getters
similar computing vue properties, mainly used to filter some of the data.
Action 
Actions may be understood as the process by which mutations in the method of processing data becomes data available asynchronous, asynchronous operation simply means that data. view layer to distribute the action by store.dispath.

const store = new Vuex.Store({ //store实例
      state: {
         count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })

modules
project particularly complex time, allowing each module has its own state, mutation, action, getters, so that the structure is very clear and easy to manage.

const moduleA = {
  state: { ... },
  mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB })

Nine, vue-cli how to add custom instruction?

1. Create a local instruction

var app = new Vue({
    el: '#app',
    data: {    
    },
    // 创建指令(可以多个)
    directives: {
        // 指令名称 dir1: { inserted(el) { // 指令中第一个参数是当前使用指令的DOM console.log(el); console.log(arguments); // 对DOM进行操作 el.style.width = '200px'; el.style.height = '200px'; el.style.background = '#000'; } } } }) 

2. Global Order

Vue.directive('dir2', {
    inserted(el) {
        console.log(el);
    }
})

3. Use of instruction

<div id="app">
    <div v-dir1></div> <div v-dir2></div> </div> 

Ten, vue how to customize a filter?

html code:

<div id="app">
     <input type="text" v-model="msg" /> {{msg| capitalize }} </div> 

JS code:

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) } } })

Filter defined globally

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

Filter the received value of the expression (msg) as the first parameter. filter will receive capitalize msg value as the first parameter.

XI understanding of the keep-alive?

keep-alive is a component built-Vue, components can be included on hold, or avoiding re-rendering.
After vue 2.1.0 version, keep-alive two newly added attributes: include (cache component included) and exclude (not exclude assembly cache, greater than the priority include).

Instructions

<keep-alive include='include_components' exclude='exclude_components'> <component> <!-- 该组件是否缓存取决于include和exclude属性 --> </component> </keep-alive>

Parameter Description
include - string or a regular expression, only the component name matches are cached
exclude - string or a regular expression, any component matching names will not be cached
include and exclude attributes allows components to conditionally cache. Both can be "," to separate strings, regular expressions, arrays. When using regular or an array, remember to use the v-bind.

Examples of Use

<!-- 逗号分隔字符串,只有组件a与b被缓存。 -->
<keep-alive include="a,b"> <component></component> </keep-alive> <!-- 正则表达式 (需要使用 v-bind,符合匹配规则的都会被缓存) --> <keep-alive :include="/a|b/"> <component></component> </keep-alive> <!-- Array (需要使用 v-bind,被包含的都会被缓存) --> <keep-alive :include="['a', 'b']"> <component></component> </keep-alive> 

Twelve, a word will be able to answer interview questions

1.css components act only on the current
A: writing style label scoped to example: <style scoped> </ style >

2.v-if and v-show differences
A: v-if conditions are rendered in accordance with, v-show is a display of block or none;

Difference 3. $ route and $ router's
Answer: $ route is "an object routing information," including path, params, hash, query, fullPath, matched, name and other information routing parameters. Router and $ a "routing instance" of the object comprises a routing jump method, the hook function like.

What are the two core 4.vue.js is?
A: data-driven components of the system

5.vue several commonly used commands
A: v-for, v-if , v-bind, v-on, v-show, v-else

6.vue commonly used modifiers?
A: .prevent: an event not to reload the page; .stop: stop the click event bubbling; .self: When an event occurs when the element itself, rather than the child element triggers; .capture: event listeners, events when it happened will call

7.v-on can bind multiple ways?
Answer:

8.vue key role in value?
A: When Vue.js with v-for being updated list elements have been rendered, it defaults to using "in situ multiplexing" strategy. If the order of the data item is changed, Vue DOM element will not be moved to match the sequence of data items, but simply reuse each element here, and it appears to ensure that each element has been rendered in a particular index. The main role is key to efficient update virtual DOM.

9. What is the calculation of property vue?
A: Putting too much logic in the template template will be too heavy and difficult to maintain, at the need for data processing complex, and potentially multiple use cases, try to take calculated as property. Benefits: ① clear that the data processing structure; ② dependent on the data, the data update, automatic update processing result; ③ computed attribute inside this point vm instance; ④ template when invoked, can directly write the name of the attribute is calculated; ⑤ getter is used the method of obtaining data, can also use the set method to change the data; ⑥ compared to the methods, regardless of the dependent variable of the same data, methods will be recalculated, but rely on the same data acquisition time computed from the cache, not recalculated.

10.vue other advantages and disadvantages of single-page application
A: Advantages: Vue goal is to achieve binding data and a view of the combined response assembly as simple as possible by API, the core of the system is a data binding response. The MVVM, data-driven, component, lightweight, simple, efficient, fast, modules friendly.
Disadvantages: does not support low version of the browser, only the minimum support to IE9; not conducive to SEO optimization (SEO if you want to support, is recommended to be rendered by the server component); first loaded Home takes a relatively long; not use your browser's navigation buttons need to implement their own forward and backward.

Guess you like

Origin www.cnblogs.com/qingkun/p/10966121.html