MVVM understanding and application front-end frame and the VUE

Market framework with a front-end frame inside before most of MVVM with a lot of open-source programs, have been gradually behind VUE framework in place, like on some of the more active open source update you can see a trace started using MVVM mode, the latter updated framework VUE, similar to before the end of open source Mall DSMall3.0 phone using a MVVM pattern, after 3.0 will be replaced with a framework of VUE, and that a MVVM and VUE What difference will it make?
First, for MVVM understanding?
 
MVVM is a Model-View-ViewModel acronym.
Model represents 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.
View and change the control behavior of ViewModel monitor 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 link, but interact through ViewModel.
Interaction between Model and ViewModel is bidirectional, so change View data will be synchronized to the Model, the data also varies Model immediate reaction to the View.
By the way data binding ViewModel 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 business logic, does not require manual operation DOM, synchronization of data need not be concerned states, complex data maintained entirely by the state MVVM to unified management.
Two, Vue life cycle
 
beforeCreate (before creation) in the observation and data initialization event has not yet begun.
created (after creating) operation is completed observation data, properties, and methods, initialization event, $ el property has not been shown.
beforeMount (pre-loaded) is called before beginning to mount, related 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 implement two-way data binding mainly: the use of data in conjunction with hijacking a publisher - way subscriber model.
Setter to hijack each attribute by Object.defineProperty (), getter, posted a message to subscribers when data changes, trigger the listener callback.
When an ordinary Vue Javascript object passed as its instance data option.
Vue will traverse its properties, with Object.defineProperty them into 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.
vue two-way data binding as the entrance to MVVM data binding, integration Observer, Compile and three Watcher.
Data to monitor changes in their model by Observer, a template compiler to parse command via Compile (vue is used to resolve {{}}).
End-use watcher acts as a bridge between the observer and Compile, to achieve data changes -> View update;
view interactive changes (input) -> data model change two-way binding effect.
js achieve a simple two-way binding
<body>
    <div the above mentioned id = "App">
    <the INPUT of the type = "text" the above mentioned id = "TXT">
    <the p-the above mentioned id = "Show"> </ the 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 ('


    document.addEventListener ( 'keyUp', function (E) {
        the obj.txt = e.target.value
    })
</ Script>
four parameter transfer between Vue assembly
1. parent element subassembly traditional values
parent component passed to the child components: data sub-assembly accepted by props method;
sub-assembly passed the parent component: $ emit method of passing parameters
2. data transfer between components of non-father and son, brother components by value
eventBus, is to create an event center, equivalent to a transit station, you can use it to pass the event 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: symbol in the browser. " # ", # and # later called the hash character, reading the window.location.hash;
features: hash, although in the URL, but not included in the HTTP request; browser used to guide the operation of the server safety useless, hash will not reload the page.
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.
Sixth, the difference between Vue and the Angular and React?
 
(Version constantly updated, the following differences are probably not quite right. I work uses only vue, for angular and react less cooked)
1. The difference with AngularJS 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.
vue special file format, the file contents have some agreement, after both need to compile using;
the same central idea: Everything components can be nested between component instance;
provide reasonable hook function that allows developers to customize of ground to deal with demand;
not built columns AJAX, Route and other functions to the core package, but a plug-load;
support mixins in component development of properties.
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, the Next:
to: the target is about to enter the route object route,
from: route was about to leave the current navigation route
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
State
Vuex single state tree, that is, each application will contain only instance of a store, but not a single state tree and modular conflict.
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 Examples
      State: {
         COUNT: 0
             },
      mutations: {                
         INCREMENT (State) {
          state.count ++
         }
          },
      Actions: { 
         INCREMENT (context) {
          context.commit ( 'INCREMENT')
   }
 }
})
modules
project particularly complex, they can so that each module has its own state, mutation, action, getters, so that the structure is very clear and easy to manage.
ModuleA = {const
  State: {...},
  mutations: {...},
  Actions: {...},
  getters: {...}
 }
const = {ModuleB
  State: {...},
  mutations: ...} {,
  Actions: {...}
 }

Store new new Vuex.Store = const ({
  modules: {
    A: ModuleA,
    B: ModuleB
})
nine, vue-cli To add a custom command?
1. Create a local instruction
var App = new new Vue ({
    EL: '#app',
    Data: {    
    },
    // creation instruction (may be a plurality)
    directives: {
        // Instruction Name
        dir1: {
            inserted The (EL) {
                // the first parameter is the command instruction currently used DOM
                the console.log (EL);
                the console.log (arguments);
                // the DOM operation
                el.style.width = '200px';
                el.style.height = '200px ';
                el.style.background =' # 000 ';
            }
        }
    }
})
2. global instruction
Vue.directive ( 'dir2', {
    inserted The (EL) {
        the console.log (EL);
    }
})
3. Use the command
<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>
the JS Code:
var VM = new new Vue ({
    EL: "#app",
    Data: {
        MSG: ''
    },
    Filters: {
      capitalize: function (value) {
        (! value) IF return ''

        value.charAt return (0) .toUpperCase () value.slice + (. 1)
      }
    }
})
globally defined filter
Vue.filter ( 'capitalize', function (value) {
  IF (! value) return ''
  value = value .toString ()
  return value.charAt (0) .toUpperCase () value.slice + (. 1)
})
filter receives the 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?
 
Vue keep-alive is a built-in component, the component 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).
Use
<= Keep-Alive include 'include_components' exclude = 'exclude_components'>
  <Component>
    <-! Cache depends on whether the component properties include and exclude ->
  <
</ keep-alive>
of parameters
include - a string or a regular expression matching only the component name will be cached
exclude - a string or a regular expression, any component matching names will not be cached
allowed to include and exclude attributes components conditionally cache.
Both can be "," to separate strings, regular expressions, arrays.
When using regular or an array, remember to use the v-bind.
Use Example
<! - comma delimited string, only the components a and b are cached. ->
<= the include Keep-Alive "A, B">
  <Component> </ Component>
</ Keep-Alive>

<! - Regular Expressions (need to use the v-bind, meet the matching rules are cached) ->
<the Keep-Alive: the include = "/ A | b /">
  <the Component> </ the Component>
</ the Keep -alive>

<-! Array (need to use v-bind, is included are cached) ->
<Keep-Alive: the include = "[ 'A', 'B']">
  <Component> </ Component>
</ keep-alive>
XII word can answer the interview questions
 
1.css only work current component
a: in writing style scoped tags can for 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 routing information parameter.
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, the bind-v, v-ON, v-Show, v-the 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, rather than sub-elements in the element itself triggers;
.capture:

A:
role of key values 8.vue?
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;
You can not use your browser's navigation buttons need to implement their own forward and backward.

Guess you like

Origin blog.51cto.com/13938514/2405781