One .Vue Responsive principle

First of all, we need to understand several concepts :

Data responsive : Data model is only common Javascript object , And when we modify the data , The view will be updated , Avoid the tedious DOM operation , Improve development efficiency .

Two way binding : Data change , View change , And the data changed , We can use v-model Create a two-way data binding on the form .

Data driven is Vue One of the most unique features : In the development process, we only need to focus on the data itself , Don't care how the data is rendered to the view .

vue2.X The response principle in is based on defineProperty, compatible IE8 Above version , The core principle code is as follows :

 let data={
msg:'hello',
count:10
}
let vm={}
proxyData(data)
function proxyData(data){
Object.keys(data).forEach(key=>{
Object.defineProperty(vm,key,{
enumerable:true,
configurable:true,
writeable:true,
// Execute when getting value
get(){
console.log('get:',key,data[key])
return data[key]
},
// Execute when setting the value
set(newValue){
data[key]=newValue
console.log('set:',key,newValue)
document.querySelector('#app').textContent=data[key]
}
})
})
}
vm.msg // obtain (get Method ) hello
vm.msg='hello World' // Set new attribute values and render to the page (set Method )
vm.msg //hello World

vue3.X The response principle in is based on Proxy, Listen directly to the object , Not attributes ,ES6 Newly added ,IE I won't support it , Performance is optimized by the browser , Performance ratio defineProperty It is better to , Compared with the words of code defineProperty Be concise , There is no need to loop through the values of multiple attributes .

 let data={
msg:'hello',
count:0
} // simulation Vue example
let vm=new Proxy(data,{
// Functions that perform proxy behavior
// When accessing vm Members of the group will perform
get(target,key){
console.log('get,key:',key,target[key])
return target[key]
},
set(target,key,newValue){
console.log('set,key:',key,newValue)
if(target[key] === newValue){
return
}
target[key]=newValue
document.querySelector("#app").textContent=target[key]
}
})
// test
vm.msg='Hello World'
console.log(vm.msg)

Two . Publish subscribe mode and observer mode

1. Release / A subscription model
This concept is a little abstract , Here is an example to illustrate , Parents are more concerned about their children's grades , Ask your child if his grades come out every day , Suppose you can subscribe to your child's grades in your child's class , Once the test results come out , It is equivalent to triggering an event , Finally, the teacher of the class informed the parents in the form of text message ,

You don't need to ask your child if his grades come out every day , Parents are subscribers to events , The teacher is the publisher of the event , The child's class can be imagined as the center of an event .vue Custom events in are based on publishing / Subscription mode . Let's simulate the operation mechanism of publish subscribe mode :

// Event trigger 
class EventEmitter(){
constructor(){
// Initialize object { 'click':[fn1,fn2],'change':[fn] }
this.subs=Object.create(null)
}
// Registration events
$on(eventType,handler){
this.subs[eventType] = this.subs[eventType] || []
this.subs[eventType].push(handler)
}
// Triggering event
$emit(eventType){
if(this.subs[eventType]){
this.subs[eventType].forEach(handler => {
handler()
})
}
}
}
// test let em =new EventEmitter() em.$on('click',()=>{
console.log('click1')
})
em.$on('click',()=>{
console.log('click2')
})
em.$emit('click') // Print the results click1,click2

Two . Observer mode

The difference between observer mode and subscription mode is that there is no event center , Only publishers and subscribers , And publishers need to know the existence of subscribers .

Concept :

The observer --Watcher

update(): When the event occurs , Specific things to do .

Publisher --Dep

subs Array : Store all observers

addSub(): Add observers

notify(): When an event occurs , Call all the observers update() Method

// Publisher - The goal is 
class Dep{
constructor() {
// Record all subscribers
this.subs=[]
}
// Add subscribers
addsub(sub){
if(sub && sub.update){
this.subs.push(sub)
}
}
// Issue notice
notify(){
this.subs.forEach(sub=>{
sub.update()
})
}
}
// subscriber - The observer
class Watcher{
update(){
console.log('update')
}
}
// test
let dep=new Dep()
let watcher=new Watcher()
dep.addsub(watcher)
dep.notify() // Print the results update

summary :

The observer pattern is scheduled by specific targets , For example, when an event triggers ,Dep Will call the observer's method , Therefore, there is a dependency between the subscriber and publisher of the observer .

The publish subscribe mode is called by the unified dispatching center , So publishers and subscribers don't need to know each other's presence .

Talking about vue More articles on the principle of responsiveness and publish subscribe mode and observer mode

  1. Talking about Vue Response type ( Array variation method )

    A lot of new uses Vue My classmates will find that , When changing the value of an array , The value did change , But the view is indifferent , Is it really because the array is too high and cold ? Check the official documents to find out , It's not that the goddess is too cold , But you didn't do it the right way . Seems to want the goddess to move , The key is to use ...

  2. Vue Source code -- Reading vue Responsive principle

    Link to the original text :https://geniuspeng.github.io/2018/01/05/vue-reactivity/ Vue There is an in-depth section on the principle of responsiveness in the official statement of . Here, the government also mentioned : When you put an ordinary ...

  3. Detailed explanation Vue Responsive principle

    Abstract : understand Vue Responsive principle ! author : Boating in the waves original text : Explain profound theories in simple language Vue Responsive principle Fundebug Reprint by authorization , The copyright belongs to the original author . Preface Vue One of the most unique features , It's a non-invasive, responsive system . The data model is just ...

  4. vue Responsive principle , Get rid of optimization , Just look at the core

    Vue Responsive principle As a coder of writing business , There's almost no need to know the principle . But when you're looking for a job , But we need to make the original bullet , You need to know something about everything . So you can review before you look for a job , As long as it's about vue Of , I'm sure I'll ask the response principle . The core : / ...

  5. thorough Vue Responsive principle

    thorough Vue.js Responsive principle One . Create a Vue application new Vue({ data() { return { name: 'yjh', }; }, router, store, render: h =& ...

  6. elementary analysis Vue Responsive principle ( 3、 ... and )

    Vue One of the principles of response defineReactive defineReactive Anyway , The final responsive data has to go through defineReactive To achieve , Actually, we need to use ES5 Newly added Object.definePro ...

  7. In depth analysis of vue Responsive principle

    Abstract : This paper mainly through the combination of vue Official documents and source code , Yes vue In depth analysis of the response principle . 1. Definition As vue The most unique features , The response can be said to be vue The soul of , On the surface, it's after the data changes , The corresponding interface will be re rendered , So respond ...

  8. The depth resolution Vue Responsive principle

    The depth resolution Vue Responsive principle This article is an excerpt from the team's open source project  InterviewMap. The current content of the project includes JS. The Internet . Browser related . performance optimization . Security . frame .Git. data structure . Algorithm, etc , Whether it's basic or advanced ...

  9. vue Response principle analysis

    # Vue Response principle analysis First of all, four core concepts are defined js file - 1. observer.js The observer function , Used to set data Of get and set function , And the watcher Store in dep in - 2. watcher ...

  10. javascript Publish subscribe mode and observer mode in

    Here's a look at JavaScript Publish subscribe mode and observer mode in , The observer pattern is 24 One of the basic design patterns . The background of design patterns Design pattern is not the technical term of software development , In fact, design patterns were first born in architecture . The definition of design patterns is ...

Random recommendation

  1. c# Use generic collections , Be lazy for yourself .

    Some people say " The lazier " The faster your programmers progress ! Actually, it makes sense . firsthand experience , From the beginning of working to now , Change by yourself " lazy " A lot of , But I feel that the code written has improved a lot . At first , Same code , assignment ...

  2. angular Instruction scope scope

    Reprinted from :https://segmentfault.com/a/1190000002773689 Let's analyze the scope of instructions in detail . Before that, I hope you're right AngularJS Of Directive There is a certain amount of ...

  3. div Horizontally and vertically centered

    <style> .vertical-center{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, ...

  4. css003 Selectors : Specify which styles to set

    css003 Selectors : Specify which styles to set 1. Two parts of each style : Selector and sound block 1. tag chooser : Overall control 2. Class selectors : Precise control (.+ Letter . Numbers . Hyphens or underscores ) Css The allowed class names are .+ Letter . Numbers . even ...

  5. Android Learning notes ( 8、 ... and )—— Four basic layouts

    // This series of blog posts is < first line Android Code > Learning notes of , Any errors , Welcome to correct ! Layout is a container that can be used to place many controls , It can adjust the position of internal controls according to certain rules , Or nested sub layout , So as to write a beautiful world ...

  6. Maven Problem solving summary

    Maven In the use , Record the problems encountered and solutions pom.xml Solution to the problem of error reporting at the top :http://stackoverflow.com/questions/5074063/maven-error-fai ...

  7. java Achieve simple single sign on

    java Achieve simple single sign on Abstract : Single sign on (SSO) The technology of is more and more widely used in various fields of software system . This paper analyzes the requirements and application fields of single sign on from the perspective of business : This paper analyzes the internal mechanism and implementation of single sign on technology from the perspective of technology itself ...

  8. C/C++ I / O redirection in

    Catalog One C/C++ I / O redirection in 1.1 C Language I / O redirection 1.2 C++ Language I / O redirection Reference material notes : Originality is not easy. , Please note the original author and source of reprint , Thank you for your support ! One C/C++ I / O redirection in ...

  9. [POI2012]BON-Vouchers---- Dare you simulate ?

    link :https://www.luogu.org/problemnew/show/P3536 The question : Definition n The number is a lucky number , Altogether n Approval , Set the first i There are x individual , Then they will take the rest in turn x The smallest multiple of x individual , ...

  10. OPENSSL Generate https Client certificate

    Now let's get the server certificate .( The premise is that the server is https, When using client authentication ), When the server doesn't give it , Let's get it ourselves ( Don't blame him !, ha-ha , To make fun of , Will give you ) openssl s_client -connect domain name ...